-
Notifications
You must be signed in to change notification settings - Fork 52
/
GithubPRPlanPlugin.groovy
199 lines (159 loc) · 6.06 KB
/
GithubPRPlanPlugin.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
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
import static TerraformEnvironmentStage.PLAN
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
class GithubPRPlanPlugin implements TerraformPlanCommandPlugin, TerraformEnvironmentStagePlugin, Resettable {
private static String myRepoSlug
private static String myRepoHost
private static String githubTokenEnvVar = "GITHUB_TOKEN"
private static final int MAX_COMMENT_LENGTH = 65535
public static void init() {
GithubPRPlanPlugin plugin = new GithubPRPlanPlugin()
TerraformEnvironmentStage.addPlugin(plugin)
TerraformPlanCommand.addPlugin(plugin)
}
public static withRepoSlug(String newRepoSlug) {
GithubPRPlanPlugin.myRepoSlug = newRepoSlug
return this
}
public static withRepoHost(String newRepoHost) {
myRepoHost = newRepoHost
return this
}
public static withGithubTokenEnvVar(String githubTokenEnvVar) {
GithubPRPlanPlugin.githubTokenEnvVar = githubTokenEnvVar
return this
}
@Override
public void apply(TerraformEnvironmentStage stage) {
stage.decorate(PLAN, addComment(stage.getEnvironment()))
}
@Override
public void apply(TerraformPlanCommand command) {
command.withPrefix("set -o pipefail;")
command.withStandardErrorRedirection('plan.err')
command.withSuffix('| tee plan.out')
}
public Closure addComment(String env) {
return { closure ->
try {
closure()
} catch (err) {
echo "terraform plan failed:"
sh "cat plan.err"
throw err
}
if (isPullRequest()) {
String url = getPullRequestCommentUrl()
String comment = getCommentBody(env)
postPullRequestComment(url, comment)
}
}
}
public String getRepoSlug() {
if (myRepoSlug != null) {
return myRepoSlug
}
def parsedScmUrl = Jenkinsfile.instance.getParsedScmUrl()
def organization = parsedScmUrl['organization']
def repo = parsedScmUrl['repo']
return "${organization}/${repo}"
}
public String getRepoHost() {
if (myRepoHost != null) {
return myRepoHost
}
def parsedScmUrl = Jenkinsfile.instance.getParsedScmUrl()
def protocol = parsedScmUrl['protocol']
def domain = parsedScmUrl['domain']
// We cannot post using the git protocol, change to https
if (protocol == "git") {
protocol = "https"
}
return "${protocol}://${domain}"
}
public String getBranchName() {
return Jenkinsfile.instance.getEnv().BRANCH_NAME
}
public boolean isPullRequest() {
def branchName = getBranchName()
return branchName.startsWith('PR-')
}
public String getPullRequestNumber() {
def branchName = getBranchName()
return branchName.replace('PR-', '')
}
public String getPullRequestCommentUrl() {
def repoHost = getRepoHost()
def repoSlug = getRepoSlug()
def pullRequestNumber = getPullRequestNumber()
return "${repoHost}/api/v3/repos/${repoSlug}/issues/${pullRequestNumber}/comments".toString()
}
public String readFile(String filename) {
def original = Jenkinsfile.instance.original
if (original.fileExists(filename)) {
return original.readFile(filename)
}
return null
}
public String getPlanOutput() {
def planOutput = readFile('plan.out')
def planError = readFile('plan.err')
// Skip any file outputs when the file does not exist
def outputs = [planOutput, planError] - null
// Strip any ANSI color encodings and whitespaces
def results = outputs.collect { output ->
output.replaceAll(/\u001b\[[0-9;]+m/, '')
.replace(/^\[[0-9;]+m/, '')
.trim()
}
// Separate by STDERR header if plan.err is not empty
results.findAll { it != '' }
.join('\nSTDERR:\n')
}
public String getBuildResult() {
Jenkinsfile.instance.original.currentBuild.currentResult
}
public String getBuildUrl() {
Jenkinsfile.instance.original.build_url
}
public String getCommentBody(String environment) {
def planOutput = getPlanOutput()
def buildResult = getBuildResult()
def buildUrl = getBuildUrl()
def lines = []
lines << "**Jenkins plan results for ${environment}** - ${buildResult} ( ${buildUrl} ):"
lines << ''
lines << '```'
lines << planOutput
lines << '```'
lines << ''
return lines.join('\n')
}
public postPullRequestComment(String pullRequestUrl, String commentBody) {
def closure = { ->
echo "Creating comment in GitHub"
// GitHub can't handle comments of 65536 or longer; chunk
commentBody.split("(?<=\\G.{${MAX_COMMENT_LENGTH}})").each { chunk ->
def data = JsonOutput.toJson([body: chunk])
def tmpDir = pwd(tmp: true)
def bodyPath = "${tmpDir}/body.txt"
writeFile(file: bodyPath, text: data)
def cmd = "curl -H \"Authorization: token \$${githubTokenEnvVar}\" -X POST -d @${bodyPath} -H 'Content-Type: application/json' -D comment.headers ${pullRequestUrl}"
def output = sh(script: cmd, returnStdout: true).trim()
def headers = readFile('comment.headers').trim()
if (! (headers.contains('HTTP/1.1 201 Created') || headers.contains('HTTP/2 201'))) {
error("Creating GitHub comment failed: ${headers}\n")
}
// ok, success
def decoded = new JsonSlurper().parseText(output)
echo "Created comment ${decoded.id} - ${decoded.html_url}"
}
}
closure.delegate = Jenkinsfile.original
closure()
}
public static void reset() {
myRepoSlug = null
myRepoHost = null
}
}