Skip to content

Commit

Permalink
Implement caching for npmWritePackageJson and npmInstall
Browse files Browse the repository at this point in the history
  • Loading branch information
jokade committed Apr 2, 2017
1 parent 903e7b9 commit beb33e8
Show file tree
Hide file tree
Showing 14 changed files with 328 additions and 45 deletions.
22 changes: 22 additions & 0 deletions LICENSE
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2017 Johannes Kastner <jokade@karchedon.de>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

2 changes: 1 addition & 1 deletion README.md
@@ -1,2 +1,2 @@
# sbt-npm
# sbt-node
sbt plugin for integration with Node.js / npm
19 changes: 13 additions & 6 deletions build.sbt
Expand Up @@ -16,25 +16,32 @@ lazy val sharedSettings = Seq(
testFrameworks += new TestFramework("utest.runner.Framework"),
scalacOptions ++= (if (isSnapshot.value) Seq.empty else Seq({
val a = baseDirectory.value.toURI.toString.replaceFirst("[^/]+/?$", "")
val g = "https://raw.githubusercontent.com/jokade/sbt-npm"
val g = "https://raw.githubusercontent.com/jokade/sbt-node"
s"-P:scalajs:mapSourceURI:$a->$g/v${version.value}/"
}))
)

lazy val plugin = project
.settings(sharedSettings ++ scriptedSettings ++ publishingSettings: _*)
.settings(
name := "sbt-npm",
name := "sbt-node",
sbtPlugin := true,
addSbtPlugin("org.scala-js" % "sbt-scalajs" % Version.scalajs)
)

//lazy val sassPlugin = project
// .dependsOn(plugin)
// .settings(sharedSettings ++ scriptedSettings ++ publishingSettings: _*)
// .settings(
// name := "sbt-node-sass",
// sbtPlugin := true
// )

lazy val root = project.in(file("."))
.aggregate(plugin)
.settings(sharedSettings ++ dontPublish: _*)
.settings(
name := "SBT NPM"
name := "sbt-node"
)


Expand All @@ -48,16 +55,16 @@ lazy val publishingSettings = Seq(
Some("releases" at nexus + "service/local/staging/deploy/maven2")
},
pomExtra := (
<url>https://github.com/jokade/sbt-npm</url>
<url>https://github.com/jokade/sbt-node</url>
<licenses>
<license>
<name>MIT License</name>
<url>http://www.opensource.org/licenses/mit-license.php</url>
</license>
</licenses>
<scm>
<url>git@github.com:jokade/sbt-npm</url>
<connection>scm:git:git@github.com:jokade/sbt-npm.git</connection>
<url>git@github.com:jokade/sbt-node</url>
<connection>scm:git:git@github.com:jokade/sbt-node.git</connection>
</scm>
<developers>
<developer>
Expand Down
45 changes: 33 additions & 12 deletions plugin/src/main/scala/de/surfice/sbtnpm/NpmPlugin.scala
Expand Up @@ -3,13 +3,15 @@
// Description:
package de.surfice.sbtnpm

import de.surfice.sbtnpm.utils.{ExternalCommand, FileWithLastrun}
import org.scalajs.sbtplugin.ScalaJSPlugin
import sbt._
import sbt.Keys._
import Keys._
import Cache._

object NpmPlugin extends AutoPlugin {

//override lazy val requires = ScalaJSPlugin
override lazy val requires = ScalaJSPlugin

// Exported keys
/**
Expand All @@ -24,7 +26,7 @@ object NpmPlugin extends AutoPlugin {
*
* @group settings
*/
val npmTargetDirectory: SettingKey[File] =
val npmTargetDir: SettingKey[File] =
settingKey[File]("Target directory for node_modules")

/**
Expand Down Expand Up @@ -57,23 +59,23 @@ object NpmPlugin extends AutoPlugin {
val npmPackageJson: SettingKey[PackageJson] =
settingKey[PackageJson]("Defines the contents of the npm package.json file")

val npmWritePackageJson: TaskKey[File] =
taskKey[File]("Create the npm package.json file.")
val npmWritePackageJson: TaskKey[FileWithLastrun] =
taskKey[FileWithLastrun]("Create the npm package.json file.")

/**
*
* @group tasks
*/
val npmInstall: TaskKey[Unit] =
taskKey[Unit]("Install npm dependencies")
val npmInstall: TaskKey[Long] =
taskKey[Long]("Install npm dependencies")
}

import autoImport._

override lazy val projectSettings: Seq[Def.Setting[_]] = Seq(
npmTargetDirectory := baseDirectory.value,
npmTargetDir := baseDirectory.value,

npmPackageJsonFile := npmTargetDirectory.value / "package.json",
npmPackageJsonFile := npmTargetDir.value / "package.json",

npmDependencies := Nil,

Expand All @@ -83,13 +85,32 @@ object NpmPlugin extends AutoPlugin {
path = npmPackageJsonFile.value,
name = name.value,
version = version.value,
dependencies = npmDevDependencies.value,
description = description.value,
dependencies = npmDependencies.value,
devDependencies = npmDevDependencies.value
),

npmWritePackageJson := {
npmPackageJson.value.writeFile()(streams.value.log)
npmPackageJsonFile.value
import Cache._
val file = npmPackageJsonFile.value
val lastrun = npmWritePackageJson.previous
if(lastrun.isEmpty || lastrun.get.needsUpdateComparedToConfig(baseDirectory.value)) {
npmPackageJson.value.writeFile()(streams.value.log)
FileWithLastrun(file)
}
else
lastrun.get
},

npmInstall := {
val file = npmWritePackageJson.value
val lastrun = npmInstall.previous
if(lastrun.isEmpty || file.lastrun>lastrun.get) {
ExternalCommand.npm.install(npmTargetDir.value,streams.value.log)
new java.util.Date().getTime
}
else
lastrun.get
}
)
}
Expand Down
2 changes: 2 additions & 0 deletions plugin/src/main/scala/de/surfice/sbtnpm/PackageJson.scala
Expand Up @@ -9,6 +9,7 @@ import PackageJson._
case class PackageJson(path: sbt.File,
name: String,
version: String = "0.0.1",
description: String = "",
dependencies: Dependencies = Nil,
devDependencies: Dependencies = Nil
) extends JsonFile {
Expand All @@ -17,6 +18,7 @@ case class PackageJson(path: sbt.File,
Obj(
'name -> name,
'version -> version,
'description -> description,
'dependencies -> Obj(dependencies),
'devDependencies -> Obj(devDependencies)
)
Expand Down
134 changes: 134 additions & 0 deletions plugin/src/main/scala/de/surfice/sbtnpm/sass/SassPlugin.scala
@@ -0,0 +1,134 @@
// Project: SBT NPM
// Module:
// Description:
package de.surfice.sbtnpm.sass

import de.surfice.sbtnpm.NpmPlugin
import de.surfice.sbtnpm.NpmPlugin.autoImport._
import de.surfice.sbtnpm.utils.{ExternalCommand, NodeCommand}
import org.scalajs.sbtplugin.{ScalaJSPluginInternal, Stage}
import sbt._
import sbt.Keys._

object SassPlugin extends AutoPlugin {

override lazy val requires = NpmPlugin

/**
* @groupname tasks Tasks
* @groupname settings Settings
*/
object autoImport {
/**
* Version of the `node-sass` npm module.
*/
val nodeSassVersion: SettingKey[String] =
settingKey[String]("node-sass version")

/**
* Defines the node-sass command to be used
*/
val nodeSassCmd: SettingKey[NodeCommand] =
settingKey[NodeCommand]("node-sass command")

val nodeSassTarget: SettingKey[File] =
settingKey[File]("target directory for compiled sass files (may be scoped to fastOptJS and fullOptJS)")

val nodeSassSourceDirectories: SettingKey[Seq[File]] =
settingKey[Seq[File]]("list of source directories that contain files to be processed by sass (may be scoped to fastOptJS and fullOptJS)")

val nodeSassInputs: TaskKey[Seq[Attributed[(File,String)]]] =
taskKey("Contains all sass input files to be processed (may be scoped to fastOptJS and fullOptJS)")

val nodeSass: TaskKey[Unit] =
taskKey[Unit]("Runs the sass compiler")
}

import autoImport._

override lazy val projectSettings: Seq[Def.Setting[_]] = Seq(
nodeSassVersion := "~4.5.2",

nodeSassCmd := NodeCommand(npmTargetDir.value,"node-sass","node-sass"),

defineSassSourceDirectories(Compile),

defineSassTarget(Compile),

defineSassInputs(Compile),

defineSassTask(Compile,nodeSassTarget in Compile),

npmDevDependencies += "node-sass" -> nodeSassVersion.value
) ++
perScalaJSStageSettings(Stage.FullOpt) ++
perScalaJSStageSettings(Stage.FastOpt)


private def perScalaJSStageSettings(stage: Stage): Seq[Def.Setting[_]] = {

val stageTask = ScalaJSPluginInternal.stageKeys(stage)

Seq(
defineSassSourceDirectories(stageTask),
defineSassTarget(stageTask),
defineSassInputs(stageTask),
nodeSassTarget in stageTask := (crossTarget in (Compile,stageTask)).value,
defineSassTask(stageTask,nodeSassTarget in stageTask)
)
}

private def defineSassTask(scope: Any, targetDir: SettingKey[File]) = {
val (task, inputs, targetDir) = scope match {
case scoped: Scoped => (nodeSass in scoped, nodeSassInputs in (Compile,scoped), nodeSassTarget in (Compile,scoped))
case config: Configuration => (nodeSass in config, nodeSassInputs in config, nodeSassTarget in config)
}
task := {
npmInstall.value
val cwd = targetDir.value
val sass = nodeSassCmd.value
val logger = streams.value.log
// logger.info(s"compiling sass files: ${inputs.value.data.mkString(", ")}")
inputs.value.foreach { f =>
val (src,dest) = f.data
sass.run(src.getAbsolutePath, (cwd / dest).getAbsolutePath)(cwd,logger)
}
}
}

private def defineSassInputs(scope: Any) = {
val (task,sourceDirs) = scope match {
case scoped: Scoped => (nodeSassInputs in scoped,nodeSassSourceDirectories in (Compile,scoped))
case config: Configuration => (nodeSassInputs in config, nodeSassSourceDirectories in config)
}
task := {
Attributed.blankSeq( sourceDirs.value flatMap { dir =>
val fs = (dir ** "*").get.filter{ f =>
val name = f.getName
f.isFile && !name.startsWith("_") && name.endsWith(".scss")
}
fs.map{ f =>
val path = f.relativeTo(dir).get.getPath

(f, path.substring(0,path.lastIndexOf("."))+".css" )
}
})
}
}

private def defineSassSourceDirectories(scope: Any) = scope match {
case scoped: Scoped =>
nodeSassSourceDirectories in (Compile,scoped) := (resourceDirectories in (Compile,scoped)).value
// nodeSassSourceDirectories in (Test,scoped) := (resourceDirectories in (Test,scoped)).value
case config: Configuration => nodeSassSourceDirectories in config := (resourceDirectories in config).value
}

private def defineSassTarget(scope: Any) = scope match {
case scoped: Scoped =>
nodeSassTarget in (Compile,scoped) := (crossTarget in (Compile,scoped)).value / "css"
// nodeSassTarget in (Compile,scoped) := (crossTarget in (Compile,scoped)).value / "css"
case config: Configuration =>
nodeSassTarget in config := (crossTarget in config).value / "css"
}

}
@@ -0,0 +1,36 @@
// Project: SBT NPM
// Module:
// Description:
package de.surfice.sbtnpm.utils

import sbt._

/**
* Helper for platform-independent handling of external commands.
*/
trait ExternalCommand {
def run(args: String*)(workingDir: File, logger: Logger): Unit = {
ExternalCommand.execute(cmdPath +: args, workingDir, logger)
}

def cmdPath: String
}


object ExternalCommand {
def apply(cmdName: String): ExternalCommand = new Impl(cmdName)

class Impl(val cmdPath: String) extends ExternalCommand

def execute(cmdLine: Seq[String], cwd: sbt.File, logger: Logger): Unit = {
val ret = Process(cmdLine) ! logger

if(ret != 0)
sys.error(s"Non-zero exit code from command ${cmdLine.head}")

}

object npm extends Impl("npm") {
def install(npmTargetDir: File, logger: Logger): Unit = run("install")(npmTargetDir,logger)
}
}

0 comments on commit beb33e8

Please sign in to comment.