<commit_before>package com.typesafe.sbt.packager.docker

import java.io.File
import java.util.concurrent.atomic.AtomicBoolean

import sbt._
import sbt.Keys.{clean, mappings, name, publish, publishLocal, sourceDirectory, streams, target, version}
import com.typesafe.sbt.packager.Keys._
import com.typesafe.sbt.packager.linux.LinuxPlugin.autoImport.{daemonUser, defaultLinuxInstallLocation}
import com.typesafe.sbt.packager.universal.UniversalPlugin
import com.typesafe.sbt.packager.universal.UniversalPlugin.autoImport.stage
import com.typesafe.sbt.SbtNativePackager.Universal
import com.typesafe.sbt.packager.Compat._
import com.typesafe.sbt.packager.validation._
import com.typesafe.sbt.packager.{MappingsHelper, Stager}

import scala.sys.process.Process
import scala.util.Try

/**
  * == Docker Plugin ==
  *
  * This plugin helps you build docker containers.
  *
  * == Configuration ==
  *
  * In order to configure this plugin take a look at the available [[com.typesafe.sbt.packager.docker.DockerKeys]]
  *
  * == Requirements ==
  *
  * You need docker to have docker installed on your system and be able to execute commands.
  * Check with a single command:
  *
  * {{{
  * docker version
  * }}}
  *
  * Future versions of the Docker Plugin may use the REST API, so you don't need docker installed
  * locally.
  *
  * @note this plugin is not intended to build very customizable docker images, but turn your mappings
  * configuration in a docker image with almost no ''any'' configuration.
  *
  * @example Enable the plugin in the `build.sbt`
  * {{{
  *    enablePlugins(DockerPlugin)
  * }}}
  */
object DockerPlugin extends AutoPlugin {

  object autoImport extends DockerKeysEx {
    val Docker: Configuration = config("docker")

    val DockerAlias = com.typesafe.sbt.packager.docker.DockerAlias
  }

  import autoImport._

  /**
    * The separator used by makeCopy should be always forced to UNIX separator.
    * The separator doesn't depend on the OS where Dockerfile is being built.
    */
  val UnixSeparatorChar = '/'

  override def requires: Plugins = UniversalPlugin

  override def projectConfigurations: Seq[Configuration] = Seq(Docker)

  // Some of the default values are now provided in the global setting based on
  // sbt plugin best practice: https://www.scala-sbt.org/release/docs/Plugins-Best-Practices.html#Provide+default+values+in
  override lazy val globalSettings: Seq[Setting[_]] = Seq(
    dockerPermissionStrategy := DockerPermissionStrategy.MultiStage,
    dockerChmodType := DockerChmodType.UserGroupReadExecute
  )

  override lazy val projectSettings: Seq[Setting[_]] = Seq(
    dockerBaseImage := "openjdk:8",
    dockerExposedPorts := Seq(),
    dockerExposedUdpPorts := Seq(),
    dockerExposedVolumes := Seq(),
    dockerLabels := Map(),
    dockerEnvVars := Map(),
    dockerRepository := None,
    dockerUsername := None,
    dockerAlias := DockerAlias(
      (dockerRepository in Docker).value,
      (dockerUsername in Docker).value,
      (packageName in Docker).value,
      Option((version in Docker).value)
    ),
    dockerUpdateLatest := false,
    dockerAliases := {
      val alias = dockerAlias.value
      if (dockerUpdateLatest.value) {
        Seq(alias, alias.withTag(Option("latest")))
      } else {
        Seq(alias)
      }
    },
    dockerEntrypoint := Seq(s"${(defaultLinuxInstallLocation in Docker).value}/bin/${executableScriptName.value}"),
    dockerCmd := Seq(),
    dockerExecCommand := Seq("docker"),
    dockerVersion := Try(Process(dockerExecCommand.value ++ Seq("version", "--format", "'{{.Server.Version}}'")).!!).toOption
      .map(_.trim)
      .flatMap(DockerVersion.parse),
    dockerBuildOptions := Seq("--force-rm") ++ dockerAliases.value.flatMap { alias =>
      Seq("-t", alias.toString)
    },
    dockerRmiCommand := dockerExecCommand.value ++ Seq("rmi"),
    dockerBuildCommand := dockerExecCommand.value ++ Seq("build") ++ dockerBuildOptions.value ++ Seq("."),
    dockerAdditionalPermissions := {
      val scripts = makeBashScripts.value
      val ms = (mappings in Docker).value
      scripts flatMap {
        case (script, _) =>
          ms collect {
            case (k, v) if k == script => DockerChmodType.UserGroupPlusExecute -> v
          }
      }
    },
    dockerCommands := {
      val strategy = dockerPermissionStrategy.value
      val dockerBaseDirectory = (defaultLinuxInstallLocation in Docker).value
      val user = (daemonUser in Docker).value
      val uidOpt = (daemonUserUid in Docker).value
      val group = (daemonGroup in Docker).value
      val gidOpt = (daemonGroupGid in Docker).value
      val base = dockerBaseImage.value
      val addPerms = dockerAdditionalPermissions.value

      val generalCommands = makeFrom(base) +: makeMaintainer((maintainer in Docker).value).toSeq
      val stage0name = "stage0"
      val stage0: Seq[CmdLike] = strategy match {
        case DockerPermissionStrategy.MultiStage =>
          Seq(
            makeFromAs(base, stage0name),
            makeWorkdir(dockerBaseDirectory),
            makeCopy(dockerBaseDirectory),
            makeUser("root"),
            makeChmodRecursive(dockerChmodType.value, Seq(dockerBaseDirectory))
          ) ++
            (addPerms map { case (tpe, v) => makeChmod(tpe, Seq(v)) }) ++
            Seq(DockerStageBreak)
        case _ => Seq()
      }

      val stage1: Seq[CmdLike] = generalCommands ++
        (uidOpt match {
          case Some(_) => Seq(makeUser("root"), makeUserAdd(user, uidOpt, gidOpt))
          case _       => Seq()<commit_msg>FIX #1205 undefined setting makeBashScripts with vanilla DockerPlugin (#1207)<commit_after>package com.typesafe.sbt.packager.docker

import java.io.File
import java.util.concurrent.atomic.AtomicBoolean

import sbt._
import sbt.Keys.{clean, mappings, name, publish, publishLocal, sourceDirectory, streams, target, version}
import com.typesafe.sbt.packager.Keys._
import com.typesafe.sbt.packager.linux.LinuxPlugin.autoImport.{daemonUser, defaultLinuxInstallLocation}
import com.typesafe.sbt.packager.universal.UniversalPlugin
import com.typesafe.sbt.packager.universal.UniversalPlugin.autoImport.stage
import com.typesafe.sbt.SbtNativePackager.Universal
import com.typesafe.sbt.packager.Compat._
import com.typesafe.sbt.packager.validation._
import com.typesafe.sbt.packager.{MappingsHelper, Stager}

import scala.sys.process.Process
import scala.util.Try

/**
  * == Docker Plugin ==
  *
  * This plugin helps you build docker containers.
  *
  * == Configuration ==
  *
  * In order to configure this plugin take a look at the available [[com.typesafe.sbt.packager.docker.DockerKeys]]
  *
  * == Requirements ==
  *
  * You need docker to have docker installed on your system and be able to execute commands.
  * Check with a single command:
  *
  * {{{
  * docker version
  * }}}
  *
  * Future versions of the Docker Plugin may use the REST API, so you don't need docker installed
  * locally.
  *
  * @note this plugin is not intended to build very customizable docker images, but turn your mappings
  * configuration in a docker image with almost no ''any'' configuration.
  *
  * @example Enable the plugin in the `build.sbt`
  * {{{
  *    enablePlugins(DockerPlugin)
  * }}}
  */
object DockerPlugin extends AutoPlugin {

  object autoImport extends DockerKeysEx {
    val Docker: Configuration = config("docker")

    val DockerAlias = com.typesafe.sbt.packager.docker.DockerAlias
  }

  import autoImport._

  /**
    * The separator used by makeCopy should be always forced to UNIX separator.
    * The separator doesn't depend on the OS where Dockerfile is being built.
    */
  val UnixSeparatorChar = '/'

  override def requires: Plugins = UniversalPlugin

  override def projectConfigurations: Seq[Configuration] = Seq(Docker)

  // Some of the default values are now provided in the global setting based on
  // sbt plugin best practice: https://www.scala-sbt.org/release/docs/Plugins-Best-Practices.html#Provide+default+values+in
  override lazy val globalSettings: Seq[Setting[_]] = Seq(
    dockerPermissionStrategy := DockerPermissionStrategy.MultiStage,
    dockerChmodType := DockerChmodType.UserGroupReadExecute
  )

  override lazy val projectSettings: Seq[Setting[_]] = Seq(
    dockerBaseImage := "openjdk:8",
    dockerExposedPorts := Seq(),
    dockerExposedUdpPorts := Seq(),
    dockerExposedVolumes := Seq(),
    dockerLabels := Map(),
    dockerEnvVars := Map(),
    dockerRepository := None,
    dockerUsername := None,
    dockerAlias := DockerAlias(
      (dockerRepository in Docker).value,
      (dockerUsername in Docker).value,
      (packageName in Docker).value,
      Option((version in Docker).value)
    ),
    dockerUpdateLatest := false,
    dockerAliases := {
      val alias = dockerAlias.value
      if (dockerUpdateLatest.value) {
        Seq(alias, alias.withTag(Option("latest")))
      } else {
        Seq(alias)
      }
    },
    dockerEntrypoint := Seq(s"${(defaultLinuxInstallLocation in Docker).value}/bin/${executableScriptName.value}"),
    dockerCmd := Seq(),
    dockerExecCommand := Seq("docker"),
    dockerVersion := Try(Process(dockerExecCommand.value ++ Seq("version", "--format", "'{{.Server.Version}}'")).!!).toOption
      .map(_.trim)
      .flatMap(DockerVersion.parse),
    dockerBuildOptions := Seq("--force-rm") ++ dockerAliases.value.flatMap { alias =>
      Seq("-t", alias.toString)
    },
    dockerRmiCommand := dockerExecCommand.value ++ Seq("rmi"),
    dockerBuildCommand := dockerExecCommand.value ++ Seq("build") ++ dockerBuildOptions.value ++ Seq("."),
    dockerAdditionalPermissions := {
      val basePath = (defaultLinuxInstallLocation in Docker).value
      (mappings in Docker).value
        .collect {
          // by default we assume everything in the bin/ folder should be executable that is not a .bat file
          case (_, path) if path.startsWith(s"$basePath/bin/") && !path.endsWith(".bat") =>
            DockerChmodType.UserGroupPlusExecute -> path
          // sh files should also be marked as executable
          case (_, path) if path.endsWith(".sh") => DockerChmodType.UserGroupPlusExecute -> path
        }
    },
    dockerCommands := {
      val strategy = dockerPermissionStrategy.value
      val dockerBaseDirectory = (defaultLinuxInstallLocation in Docker).value
      val user = (daemonUser in Docker).value
      val uidOpt = (daemonUserUid in Docker).value
      val group = (daemonGroup in Docker).value
      val gidOpt = (daemonGroupGid in Docker).value
      val base = dockerBaseImage.value
      val addPerms = dockerAdditionalPermissions.value

      val generalCommands = makeFrom(base) +: makeMaintainer((maintainer in Docker).value).toSeq
      val stage0name = "stage0"
      val stage0: Seq[CmdLike] = strategy match {
        case DockerPermissionStrategy.MultiStage =>
          Seq(
            makeFromAs(base, stage0name),
            makeWorkdir(dockerBaseDirectory),
            makeCopy(dockerBaseDirectory),
            makeUser("root"),
            makeChmodRecursive(dockerChmodType.value, Seq(dockerBaseDirectory))
          ) ++
            (addPerms map { case (tpe, v) => makeChmod(tpe, Seq(v)) }) ++
            Seq(DockerStageBreak)
        case _ => Seq()
      }

      val stage1: Seq[CmdLike] = generalCommands ++
        (uidOpt match {
          case Some(_) => Seq(makeUser("root"), makeUserAdd(user, uidOpt, gidOpt))
          case _       => Seq()
{'fraction_non_alphanumeric': 0.11040376733234498, 'fraction_numerical': 0.0017441353449027645, 'mean_word_length': 3.3308157099697886, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 22, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7250026', 'n_tokens_mistral': 3541, 'n_tokens_neox': 3289, 'n_words': 841}