Skip to content

Instantly share code, notes, and snippets.

@joescii
Created October 14, 2016 01:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joescii/4431cb2185eddb699dfb79b9c910e333 to your computer and use it in GitHub Desktop.
Save joescii/4431cb2185eddb699dfb79b9c910e333 to your computer and use it in GitHub Desktop.
Conditional sbt Settings
scalaVersion := "2.11.7"
crossScalaVersions := Seq("2.9.2", "2.10.5", "2.11.7")
publishTo := Some(Resolver.file("Unused transient repository", file("target/unusedrepo")))
def conditionalSettings[P](conditionalKey: SettingKey[P])(predicate: P => Boolean): Seq[Def.Setting[_]] = {
// How can I make this suck less?
Seq(
publishArtifact := { if(predicate(conditionalKey.value)) false else publishArtifact.value },
publishLocal := { if(predicate(conditionalKey.value)) {} else publishLocal.value },
publish := { if(predicate(conditionalKey.value)) {} else publish.value },
publishTo := { if(predicate(conditionalKey.value)) None else publishTo.value }
)
}
conditionalSettings(scalaBinaryVersion)(_ == "2.10")
@SethTisue
Copy link

fwiw

val suppressPublishing = settingKey[Boolean]("suppress publishing")
suppressPublishing := scalaBinaryVersion.value == "2.10"

def suppress[T](key: SettingKey[T], value: T): Def.Setting[T] =
  key := { if (suppressPublishing.value) value else key.value }
def suppress[T](key: TaskKey[T], value: T): Def.Setting[Task[T]] =
  key := { if (suppressPublishing.value) value else key.value }

suppress(publish,         {}   )
suppress(publishLocal,    {}   )
suppress(publishArtifact, false)
suppress(publishTo,       None )

@joescii
Copy link
Author

joescii commented Oct 14, 2016

Yeah, I went down that path too, but my IRL problem requires value: T to often be a function of other settings, and that's where it fell apart for me.

@jastice
Copy link

jastice commented Feb 20, 2017

How about

def conditionalSettings[P](conditionalKey: SettingKey[P])(predicate: P => Boolean): Seq[Def.Setting[_]] = {
    if (predicate(conditionalKey.value))
      Seq(
        publishArtifact := false,
        publishLocal := {},
        publish := {},
        publishTo := None
      )
    else Seq.empty
}

@atais
Copy link

atais commented Jul 26, 2018

@jastice it won't compile

/path/build.sbt:371: error: `value` can only be used within a task or setting macro, such as :=, +=, ++=, Def.task, or Def.setting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment