<commit_before>fs = require 'fs'
path = require 'path'

paths = require '../paths'
http = require '../httpRequest'
Help = require '../Help'
log = require "../log"
RuntimeConfig = require '../RuntimeConfig'
PackagerBase = require '../packager/Base'
Grunt = require '../Grunt'

writeJsonStringTo = require './writeJsonStringTo'

module.exports = deployModule = ->
  console.log "About to deploy module..."

  readDeploymentDescription()
    .catch((error) -> createModule())
    .then((module) ->
      nextVersion = getNextModuleVersionNumber module
      createModuleVersion(module.id, nextVersion)
        .then(pushToModuleVersion module.id)
        .then(->
          findModule(module.id)
        )
    ).then (module) ->
      writeDeploymentDescription module

      Help.SUCCESS()
      steroidsCli.log """
        Deployed module at: #{getDeploymentLocation(module)}
      """

createModule = ->
  http.requestAuthenticated(
    method: "POST"
    url: getModuleCreateUrl()
    json: true
  )
  .then (data) ->
    data.module

createModuleVersion = (moduleId, versionIdentifier) ->
  http.requestAuthenticated(
    method: "POST"
    url: getModuleVersionCreateUrl(moduleId)
    json: true
    body:
      version:
        version: versionIdentifier
  )
  .then (data) ->
    data.version

findModule = (moduleId) ->
  http.requestAuthenticated(
    method: "GET"
    url: getModuleUrl(moduleId)
    json: true
  )
  .then (data) ->
    data.module

getCurrentVersion = (module) ->
  module?.versions?[0]

getDeploymentLocation = (module) ->
  getCurrentVersion(module)?.location

getNextModuleVersionNumber = (module) ->
  Number(getCurrentVersion(module)?.version || 0) + 1

pushToModuleVersion = (moduleId) -> (moduleVersion) ->
  packageModuleToDist()
    .then(zipModuleDist)
    .then(uploadWithInstructions moduleVersion.module_zip_upload_instructions)
    .then ->
      announceUploadCompleted moduleId, moduleVersion.id

packageModuleToDist = ->
  console.log "About to run Grunt tasks..."

  gruntTask = steroidsCli.options.argv["gruntTask"] || "default"
  new Grunt()
    .run(tasks: [gruntTask])
    .then ->
      log.ok "Successfully compiled module"

      paths.application.distDir

zipModuleDist = (distDir) ->
  console.log "About to package module dist..."

  new PackagerBase({ distDir })
    .create()
    .then ->
      log.ok "Successfully packaged module"
      paths.temporaryZip

uploadWithInstructions = (uploadInstructions) -> (moduleZipPath) ->
  console.log "About to upload module package..."

  http.request(
    method: "POST"
    url: uploadInstructions.__endpoint
    formData:
      key: uploadInstructions.key
      AWSAccessKeyId: uploadInstructions.AWSAccessKeyId
      acl: uploadInstructions.acl
      policy: uploadInstructions.policy
      signature: uploadInstructions.signature
      success_action_status: uploadInstructions.success_action_status
      utf8: uploadInstructions.utf8
      file: fs.createReadStream moduleZipPath
  ).then ->
    log.ok "Successfully uploaded module package"

announceUploadCompleted = (moduleId, moduleVersionId) ->
  http.requestAuthenticated(
    method: "PUT"
    url: getModuleVersionUpdateUrl(moduleId, moduleVersionId)
    json: true
    body:
      version:
        module_zip_last_uploaded_at: (new Date).toISOString()
  )

deploymentDescriptionPath = paths.application.configs.module.deployment

readDeploymentDescription = ->
  new Promise (resolve) -><commit_msg>add: pass metadata given from module api to endpoint<commit_after>fs = require 'fs'
path = require 'path'

paths = require '../paths'
http = require '../httpRequest'
Help = require '../Help'
log = require "../log"
RuntimeConfig = require '../RuntimeConfig'
PackagerBase = require '../packager/Base'
Grunt = require '../Grunt'

writeJsonStringTo = require './writeJsonStringTo'

module.exports = deployModule = ->
  console.log "About to deploy module..."

  readDeploymentDescription()
    .catch((error) -> createModule())
    .then((module) ->
      nextVersion = getNextModuleVersionNumber module
      createModuleVersion(module.id, nextVersion)
        .then(pushToModuleVersion module.id)
        .then(->
          findModule(module.id)
        )
    ).then (module) ->
      writeDeploymentDescription module

      Help.SUCCESS()
      steroidsCli.log """
        Deployed module at: #{getDeploymentLocation(module)}
      """

createModule = ->
  http.requestAuthenticated(
    method: "POST"
    url: getModuleCreateUrl()
    json: true
  )
  .then (data) ->
    data.module

createModuleVersion = (moduleId, versionIdentifier) ->
  http.requestAuthenticated(
    method: "POST"
    url: getModuleVersionCreateUrl(moduleId)
    json: true
    body:
      version:
        version: versionIdentifier
  )
  .then (data) ->
    data.version

findModule = (moduleId) ->
  http.requestAuthenticated(
    method: "GET"
    url: getModuleUrl(moduleId)
    json: true
  )
  .then (data) ->
    data.module

getCurrentVersion = (module) ->
  module?.versions?[0]

getDeploymentLocation = (module) ->
  getCurrentVersion(module)?.location

getNextModuleVersionNumber = (module) ->
  Number(getCurrentVersion(module)?.version || 0) + 1

pushToModuleVersion = (moduleId) -> (moduleVersion) ->
  packageModuleToDist()
    .then(zipModuleDist)
    .then(uploadWithInstructions moduleVersion.module_zip_upload_instructions)
    .then ->
      announceUploadCompleted moduleId, moduleVersion.id

packageModuleToDist = ->
  console.log "About to run Grunt tasks..."

  gruntTask = steroidsCli.options.argv["gruntTask"] || "default"
  new Grunt()
    .run(tasks: [gruntTask])
    .then ->
      log.ok "Successfully compiled module"

      paths.application.distDir

zipModuleDist = (distDir) ->
  console.log "About to package module dist..."

  new PackagerBase({ distDir })
    .create()
    .then ->
      log.ok "Successfully packaged module"
      paths.temporaryZip

uploadWithInstructions = (uploadInstructions) -> (moduleZipPath) ->
  console.log "About to upload module package..."
  data =
    key: uploadInstructions.key
    AWSAccessKeyId: uploadInstructions.AWSAccessKeyId
    acl: uploadInstructions.acl
    policy: uploadInstructions.policy
    signature: uploadInstructions.signature
    success_action_status: uploadInstructions.success_action_status
    utf8: uploadInstructions.utf8

  if uploadInstructions.metadata?
    for key, value of uploadInstructions.metadata
      data[key] = value

  data.file = fs.createReadStream moduleZipPath

  http.request(
    method: "POST"
    url: uploadInstructions.__endpoint
    formData: data
  ).then ->
    log.ok "Successfully uploaded module package"

announceUploadCompleted = (moduleId, moduleVersionId) ->
  http.requestAuthenticated(
    method: "PUT"
    url: getModuleVersionUpdateUrl(moduleId, moduleVersionId)
    json: true
    body:
      version:
        module_zip_last_uploaded_at: (new Date).toISOString()
  )

deploymentDescriptionPath = paths.application.configs.module.deployment

readDeploymentDescription = ->
  new Promise (resolve) ->
{'fraction_non_alphanumeric': 0.11134661579765437, 'fraction_numerical': 0.0014130281192595733, 'mean_word_length': 3.418227215980025, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 57, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '6939717', 'n_tokens_mistral': 2090, 'n_tokens_neox': 2059, 'n_words': 459}