This repository has been archived by the owner on Nov 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathbuild.gradle
350 lines (281 loc) · 12.1 KB
/
build.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
import java.nio.file.Paths
buildscript {
ext.kotlin_version = '1.2.20'
repositories {
mavenCentral()
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.moowork.gradle:gradle-node-plugin:1.2.0'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'
}
}
def npmScope = findProperty('scope') ?: 'kotlin-externals'
def dryRun = findProperty('dryRun') ?: 'false'
def authToken = findProperty('authToken') ?: findProperty('kotlin.npmjs.auth.token') ?: ''
def deployTag = findProperty('deployTag') ?: 'dev'
def mockNpmPort = findProperty('mockNpmPort') ?: '3676'
def autoPublish = hasProperty("autoPublish") ? property("autoPublish") == "true" : false
// Reads from InputStream `sin` until the empty line is reached
// Looks for "content-length" header and returns its value as Integer
// Returns 0 is the header was not found
static def parseHeadersAndGetContentLength(def br) {
def result = 0
def line = br.readLine()
while (!line.isEmpty()) {
println(line)
def contentLengthString = "content-length: "
if (line.toLowerCase().startsWith(contentLengthString)) {
result = Integer.parseInt(line.substring(contentLengthString.length()).trim())
}
line = br.readLine()
}
return result
}
// Reads `n` bytes from Reader
// Throws IOException if unsuccessfull
// Returns a byte array of length `n`
static def readNBytes(def reader, def n) {
def result = new char[n]
def count = 0
while (count < result.length) {
def bytesRead = reader.read(result, count, result.length - count)
if (bytesRead < 0) throw new IOException("Unexpected EOF")
count += bytesRead
}
return result
}
def MOCK_NPM_RESPONSE = """HTTP/1.1 201
content-type: application/json
content-length: 2
{}
"""
static def assertEquals(def msg, def expected, def actual) {
if (expected != actual) {
throw new GradleException("$msg. Expected: '$expected'; actual: '$actual'.")
}
}
def assertFileExists(def path) {
if (!file(path).exists()) {
throw new GradleException("File doesn't exist: $path")
}
}
subprojects.stream().filter { it.parent != rootProject }.each { p ->
configure(p) {
apply plugin: 'kotlin2js'
apply plugin: 'com.moowork.node'
apply plugin: 'maven-publish'
apply plugin: 'com.jfrog.bintray'
node {
download = true
workDir = file("${rootProject.buildDir}/nodejs")
}
repositories {
mavenCentral()
}
def libraryPath = projectDir.parent
def libraryName = file(libraryPath).name
def packageJsonPath = "$libraryPath/package.json"
def readmePath = "$libraryPath/README.md"
def deployDir = "$buildDir/deploy_to_npm"
def konfigPath = "$projectDir/konfig.json"
def konfigFile = file(konfigPath)
def problems = []
def konfig
if (!konfigFile.exists()) {
konfig = [:]
problems.add("Configuration file $konfigPath doesn't exist")
} else {
konfig = new JsonSlurper().parseText(konfigFile.text)
}
if (konfig.version == null) {
problems.add("Error while processing $konfigPath")
}
def deployVersion = konfig.version ?: "0.0.0"
project.version = deployVersion
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
konfig.dependencies?.forEach {
compile(project(it))
}
}
task sourcesJar(type: Jar) {
from "$projectDir/src"
classifier = 'sources'
}
publishing {
publications {
maven(MavenPublication) {
from components.java
groupId 'kotlin.js.externals'
artifactId "kotlin-js-$libraryName"
version deployVersion
artifact sourcesJar
}
}
}
bintray {
user = findProperty('deployRepoUsername') ?: findProperty('kotlin.bintray.user')
key = findProperty('deployRepoPassword') ?: findProperty('kotlin.bintray.password')
publications = ['maven']
publish = autoPublish
pkg {
repo = findProperty('deployRepoUrl') ?: 'js-externals'
name = "kotlin-js-$libraryName"
userOrg = findProperty('deployRepoOrg') ?: 'kotlin'
licenses = ['Apache-2.0']
vcsUrl = 'https://github.com/kotlin/js-externals.git'
version {
name = deployVersion
}
}
}
def mockNpmDir = "$buildDir/mock_npm"
def publishedJsonPath = "$mockNpmDir/published.json"
def tarballPath = "$mockNpmDir/${libraryName}.tgz"
def tarballExtractedPath = "$mockNpmDir/$libraryName"
compileKotlin2Js {
kotlinOptions {
outputFile = "$destinationDir/${libraryName}.js"
moduleKind = "umd"
sourceMap = true
}
}
sourceSets {
main.kotlin.srcDirs += "$projectDir/src"
testUMD {
kotlin.srcDirs += "$projectDir/test"
kotlin.srcDirs += "$projectDir/testUMD"
kotlin.srcDirs += "$projectDir/../_testShared"
kotlin.srcDirs += "$projectDir/../_testSharedUMD"
compileClasspath = test.compileClasspath
}
testPlain {
kotlin.srcDirs += "$projectDir/test"
kotlin.srcDirs += "$projectDir/testPlain"
kotlin.srcDirs += "$projectDir/../_testShared"
kotlin.srcDirs += "$projectDir/../_testSharedPlain"
compileClasspath = test.compileClasspath
}
testCommonJS {
kotlin.srcDirs += "$projectDir/test"
kotlin.srcDirs += "$projectDir/testCommonJS"
kotlin.srcDirs += "$projectDir/../_testShared"
kotlin.srcDirs += "$projectDir/../_testSharedCommonJS"
compileClasspath = test.compileClasspath
}
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile).forEach {
if (it.name.startsWith("compileTest") && it.name.endsWith("Kotlin2Js")) {
def start = "compileTest".length()
def end = it.name.lastIndexOf("OnlyKotlin2Js")
if (end < 0) {
end = it.name.lastIndexOf("Kotlin2Js")
}
def moduleKind = it.name.substring(start, end).toLowerCase()
if (moduleKind.isEmpty()) {
moduleKind = "umd"
}
it.kotlinOptions.moduleKind = moduleKind
test.dependsOn(it)
}
}
task validate {
doFirst {
if (!file(packageJsonPath).exists()) throw new GradleException("$packageJsonPath doesn't exist")
if (!file(readmePath).exists()) throw new GradleException("Readme file $readmePath doesn't exist")
if (!problems.isEmpty()) throw new GradleException("Found problems:\n" + problems.join("\n"))
}
}
check.dependsOn(validate)
task cleanDeployDir(type: Delete) {
delete = deployDir
}
task copyTemplate(type: Copy, dependsOn: [validate, cleanDeployDir]) {
from readmePath
into deployDir
}
task preparePackageJson(dependsOn: [validate, cleanDeployDir]) {
doFirst {
def packageJson = new JsonSlurper().parseText(file(packageJsonPath).text)
packageJson.version = konfig.version
packageJson.name = "@$npmScope/$libraryName"
def deps = konfig.dependencies
if (deps != null && !deps.isEmpty()) {
if (packageJson.dependencies == null) {
packageJson.dependencies = [:]
}
deps.forEach {
def depProject = project(it)
packageJson.dependencies["@$npmScope/${depProject.name}"] = depProject.version
}
}
file("$deployDir/package.json").write(JsonOutput.toJson(packageJson))
}
}
task copySources(type: Copy, dependsOn: [compileKotlin2Js, cleanDeployDir]) {
from compileKotlin2Js.destinationDir
into deployDir
}
task preparePublish(dependsOn: [copyTemplate, preparePackageJson, copySources])
bintrayUpload.dependsOn(preparePublish)
task publishToNpm(type: NpmTask, dependsOn: preparePublish) {
workingDir = file(deployDir)
args = ['publish',
'--access=public',
"--//registry.npmjs.org/:_authToken=$authToken",
"--tag=$deployTag"]
if (dryRun == "true") {
args += ["--reg=http://localhost:$mockNpmPort",
"--//localhost:$mockNpmPort/:_password=mock!!password",
"--//localhost:$mockNpmPort/:username=mock!!user",
"--//localhost:$mockNpmPort/:[email protected]",
"--//localhost:$mockNpmPort/:always-auth=false"]
doFirst {
// Run during execution, not configuration
println("$deployDir \$ npm arguments: ${args.join(" ")}")
new Thread({
new ServerSocket(Integer.parseInt(mockNpmPort as String)).withCloseable {
it.setSoTimeout(1000)
it.accept().withCloseable { s ->
def br = new BufferedReader(new InputStreamReader(s.getInputStream()))
file(mockNpmDir).mkdir()
file(publishedJsonPath).text = new String(readNBytes(br, parseHeadersAndGetContentLength(br)))
new PrintWriter(s.getOutputStream(), true).println(MOCK_NPM_RESPONSE)
}
}
}).start()
}
doLast {
def json = new JsonSlurper().parseText(file(publishedJsonPath).text)
assertEquals("Unexpected package name", "@$npmScope/$libraryName", json.name)
assertEquals("Wrong version", deployVersion, json["dist-tags"][deployTag as String])
def tarball = json._attachments["${json.name}-${deployVersion}.tgz"].data
file(tarballPath).bytes = Base64.decoder.decode(tarball as String)
copy {
from tarTree(tarballPath)
into tarballExtractedPath
}
def packagePath = "$tarballExtractedPath/package"
assertFileExists("$packagePath/$libraryName")
assertFileExists("$packagePath/${libraryName}.js")
assertFileExists("$packagePath/${libraryName}.js.map")
assertFileExists("$packagePath/${libraryName}.meta.js")
assertFileExists("$packagePath/package.json")
file(packagePath).eachFileRecurse {
if (it.isFile()) {
def relativePath = Paths.get(packagePath).relativize(Paths.get(it.path))
def originalFile = "$deployDir/$relativePath"
if (it.text != file(originalFile).text) {
throw new GradleException("File content differs. Original: $originalFile; Published: ${it.path}")
}
}
}
}
}
}
}
}