/
ReleaseTask.groovy
114 lines (92 loc) · 3.74 KB
/
ReleaseTask.groovy
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
package co.riiid.gradle
import groovyx.net.http.ContentType
import groovyx.net.http.Method
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.zeroturnaround.zip.ZipUtil
class ReleaseTask extends DefaultTask {
// header
final String HEADER_USER_AGENT = 'gradle-github-plugin'
@TaskAction
public release() {
def baseUrl = project.github.getBaseUrl()
def accept = project.github.getAcceptHeader()
def http = new HttpBuilder(baseUrl)
def path = "/repos/" +
"${project.github.owner}/" +
"${project.github.repo}/releases"
def postBody = [
tag_name : project.github.getTagName(),
target_commitish: project.github.getTargetCommitish(),
name : project.github.getName(),
body : project.github.getBody(),
prerelease : project.github.isPrerelease(),
draft : project.github.isDraft()
]
http.request(Method.POST) {
uri.path += path
requestContentType = ContentType.JSON
body = postBody
headers.'User-Agent' = HEADER_USER_AGENT
headers.'Authorization' = "token ${project.github.token}"
headers.'Accept' = accept
response.success = { resp, json ->
println json
if (project.github.assets != null) {
postAssets(json.upload_url, project.github.assets, accept)
}
}
response.failure = { resp, json ->
System.err.println json
}
}
}
public postAssets(uploadUrl, assets, accept) {
assets.each { asset ->
def file = new File(asset as String)
def name = asset.split('/')[-1]
if (file.exists() && file.directory) {
name += ".zip"
}
def upload = uploadUrl.replace(
'{?name,label}', "?name=${name}&label=${name}")
println "upload url: ${upload}"
def url = new URL(upload as String)
def host = url.host + (url.port > 0 ? ":" + url.port + "" : "")
host = "${url.protocol}://${host}"
def path = url.path
def http = new HttpBuilder(host)
if (file.exists()) {
if (file.directory) {
def zipFile = new File(file.parentFile, file.name + ".zip")
ZipUtil.pack(file, zipFile)
file = zipFile
}
def map = URLConnection.getFileNameMap()
def contentType = map.getContentTypeFor(file.absolutePath)
http.ignoreSSLIssues()
http.request(Method.POST) { req ->
uri.path = path
uri.query = [
name: name,
]
send ContentType.BINARY, file.bytes
headers.'User-Agent' = HEADER_USER_AGENT
headers.'Authorization' = "token ${project.github.token}"
headers.'Accept' = accept
headers.'Content-Type' = contentType
response.success = { resp, json ->
println json
if (file.exists() && file.name.endsWith(".zip"))
file.delete()
}
response.failure = { resp, json ->
System.err.println json
if (file.exists() && file.name.endsWith(".zip"))
file.delete()
}
}
}
}
}
}