1/*
2 * Copyright 2017-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3 */
4
5def prop(name, defVal) {
6    def value = project.properties[name]
7    if (value == null) return defVal
8    return value
9}
10
11def distTag(version) {
12    def i = version.indexOf('-')
13    if (i > 0) return version.substring(i + 1)
14    return "latest"
15}
16
17def npmTemplateDir = file("$projectDir/npm")
18def npmDeployDir = file("$buildDir/npm")
19def npmDeployTag = distTag(version)
20
21def authToken = prop("kotlin.npmjs.auth.token", "")
22def dryRun = prop("dryRun", "false")
23
24def compileJsLegacy = tasks.hasProperty("compileKotlinJsLegacy")
25        ? compileKotlinJsLegacy
26        : compileKotlinJs
27
28task preparePublishNpm(type: Copy, dependsOn: [compileJsLegacy]) {
29    from(npmTemplateDir) {
30        expand (project.properties + [kotlinDependency: "\"kotlin\": \"$kotlin_version\""])
31    }
32    from(compileJsLegacy.destinationDir)
33    into npmDeployDir
34}
35
36task performPublishNpm(type: NpmTask, dependsOn: [preparePublishNpm]) {
37    workingDir = npmDeployDir
38    def deployArgs = ['publish',
39                      "--//registry.npmjs.org/:_authToken=$authToken",
40                      "--tag=$npmDeployTag"]
41    doFirst {
42        if (dryRun == "true") {
43            println("$npmDeployDir \$ npm arguments: $deployArgs")
44            args = ['pack']
45        } else {
46            args = deployArgs
47        }
48    }
49
50    if (authToken == "") {
51        enabled = false // skip npm publishing when token is not set
52    }
53}
54
55task publishNpm(dependsOn: performPublishNpm) {
56    doFirst {
57        if (!performPublishNpm.enabled) {
58            println("NOTE: publishNpm is skipped because 'kotlin.npmjs.auth.token' is not set")
59        }
60    }
61}
62
63