forked from runatlantis/atlantis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdown_renderer.go
256 lines (235 loc) · 9.4 KB
/
markdown_renderer.go
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
// Copyright 2017 HootSuite Media Inc.
//
// Licensed under the Apache License, Version 2.0 (the License);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an AS IS BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Modified hereafter by contributors to runatlantis/atlantis.
package events
import (
"bytes"
"fmt"
"strings"
"text/template"
"github.com/Masterminds/sprig"
"github.com/runatlantis/atlantis/server/events/models"
)
const (
planCommandTitle = "Plan"
applyCommandTitle = "Apply"
// maxUnwrappedLines is the maximum number of lines the Terraform output
// can be before we wrap it in an expandable template.
maxUnwrappedLines = 12
)
// MarkdownRenderer renders responses as markdown.
type MarkdownRenderer struct {
// GitlabSupportsCommonMark is true if the version of GitLab we're
// using supports the CommonMark markdown format.
// If we're not configured with a GitLab client, this will be false.
GitlabSupportsCommonMark bool
}
// CommonData is data that all responses have.
type CommonData struct {
Command string
Verbose bool
Log string
}
// ErrData is data about an error response.
type ErrData struct {
Error string
CommonData
}
// FailureData is data about a failure response.
type FailureData struct {
Failure string
CommonData
}
// ResultData is data about a successful response.
type ResultData struct {
Results []projectResultTmplData
CommonData
}
type projectResultTmplData struct {
Workspace string
RepoRelDir string
Rendered string
}
// Render formats the data into a markdown string.
// nolint: interfacer
func (m *MarkdownRenderer) Render(res CommandResult, cmdName CommandName, log string, verbose bool, vcsHost models.VCSHostType) string {
commandStr := strings.Title(cmdName.String())
common := CommonData{commandStr, verbose, log}
if res.Error != nil {
return m.renderTemplate(unwrappedErrWithLogTmpl, ErrData{res.Error.Error(), common})
}
if res.Failure != "" {
return m.renderTemplate(failureWithLogTmpl, FailureData{res.Failure, common})
}
return m.renderProjectResults(res.ProjectResults, common, vcsHost)
}
func (m *MarkdownRenderer) renderProjectResults(results []ProjectResult, common CommonData, vcsHost models.VCSHostType) string {
var resultsTmplData []projectResultTmplData
numPlanSuccesses := 0
for _, result := range results {
resultData := projectResultTmplData{
Workspace: result.Workspace,
RepoRelDir: result.RepoRelDir,
}
if result.Error != nil {
tmpl := unwrappedErrTmpl
if m.shouldUseWrappedTmpl(vcsHost, result.Error.Error()) {
tmpl = wrappedErrTmpl
}
resultData.Rendered = m.renderTemplate(tmpl, struct {
Command string
Error string
}{
Command: common.Command,
Error: result.Error.Error(),
})
} else if result.Failure != "" {
resultData.Rendered = m.renderTemplate(failureTmpl, struct {
Command string
Failure string
}{
Command: common.Command,
Failure: result.Failure,
})
} else if result.PlanSuccess != nil {
if m.shouldUseWrappedTmpl(vcsHost, result.PlanSuccess.TerraformOutput) {
resultData.Rendered = m.renderTemplate(planSuccessWrappedTmpl, *result.PlanSuccess)
} else {
resultData.Rendered = m.renderTemplate(planSuccessUnwrappedTmpl, *result.PlanSuccess)
}
numPlanSuccesses++
} else if result.ApplySuccess != "" {
if m.shouldUseWrappedTmpl(vcsHost, result.ApplySuccess) {
resultData.Rendered = m.renderTemplate(applyWrappedSuccessTmpl, struct{ Output string }{result.ApplySuccess})
} else {
resultData.Rendered = m.renderTemplate(applyUnwrappedSuccessTmpl, struct{ Output string }{result.ApplySuccess})
}
} else {
resultData.Rendered = "Found no template. This is a bug!"
}
resultsTmplData = append(resultsTmplData, resultData)
}
var tmpl *template.Template
switch {
case len(resultsTmplData) == 1 && common.Command == planCommandTitle && numPlanSuccesses > 0:
tmpl = singleProjectPlanSuccessTmpl
case len(resultsTmplData) == 1 && common.Command == planCommandTitle && numPlanSuccesses == 0:
tmpl = singleProjectPlanUnsuccessfulTmpl
case len(resultsTmplData) == 1 && common.Command == applyCommandTitle:
tmpl = singleProjectApplyTmpl
case common.Command == planCommandTitle:
tmpl = multiProjectPlanTmpl
case common.Command == applyCommandTitle:
tmpl = multiProjectApplyTmpl
default:
return "no template matched–this is a bug"
}
return m.renderTemplate(tmpl, ResultData{resultsTmplData, common})
}
// shouldUseWrappedTmpl returns true if we should use the wrapped markdown
// templates that collapse the output to make the comment smaller on initial
// load. Some VCS providers or versions of VCS providers don't support this
// syntax.
func (m *MarkdownRenderer) shouldUseWrappedTmpl(vcsHost models.VCSHostType, output string) bool {
// Bitbucket Cloud and Server don't support the folding markdown syntax.
if vcsHost == models.BitbucketServer || vcsHost == models.BitbucketCloud {
return false
}
if vcsHost == models.Gitlab && !m.GitlabSupportsCommonMark {
return false
}
return strings.Count(output, "\n") > maxUnwrappedLines
}
func (m *MarkdownRenderer) renderTemplate(tmpl *template.Template, data interface{}) string {
buf := &bytes.Buffer{}
if err := tmpl.Execute(buf, data); err != nil {
return fmt.Sprintf("Failed to render template, this is a bug: %v", err)
}
return buf.String()
}
// todo: refactor to remove duplication #refactor
var singleProjectApplyTmpl = template.Must(template.New("").Parse(
"{{$result := index .Results 0}}Ran {{.Command}} in dir: `{{$result.RepoRelDir}}` workspace: `{{$result.Workspace}}`\n\n{{$result.Rendered}}\n" + logTmpl))
var singleProjectPlanSuccessTmpl = template.Must(template.New("").Parse(
"{{$result := index .Results 0}}Ran {{.Command}} in dir: `{{$result.RepoRelDir}}` workspace: `{{$result.Workspace}}`\n\n{{$result.Rendered}}\n" +
"\n" +
"---\n" +
"* :fast_forward: To **apply** all unapplied plans from this pull request, comment:\n" +
" * `atlantis apply`" + logTmpl))
var singleProjectPlanUnsuccessfulTmpl = template.Must(template.New("").Parse(
"{{$result := index .Results 0}}Ran {{.Command}} in dir: `{{$result.RepoRelDir}}` workspace: `{{$result.Workspace}}`\n\n" +
"{{$result.Rendered}}\n" + logTmpl))
var multiProjectPlanTmpl = template.Must(template.New("").Funcs(sprig.TxtFuncMap()).Parse(
"Ran {{.Command}} for {{ len .Results }} projects:\n" +
"{{ range $result := .Results }}" +
"1. workspace: `{{$result.Workspace}}` dir: `{{$result.RepoRelDir}}`\n" +
"{{end}}\n" +
"{{ range $i, $result := .Results }}" +
"### {{add $i 1}}. workspace: `{{$result.Workspace}}` dir: `{{$result.RepoRelDir}}`\n" +
"{{$result.Rendered}}\n\n" +
"---\n{{end}}{{ if gt (len .Results) 0 }}* :fast_forward: To **apply** all unapplied plans from this pull request, comment:\n" +
" * `atlantis apply`{{end}}" +
logTmpl))
var multiProjectApplyTmpl = template.Must(template.New("").Funcs(sprig.TxtFuncMap()).Parse(
"Ran {{.Command}} for {{ len .Results }} projects:\n" +
"{{ range $result := .Results }}" +
"1. workspace: `{{$result.Workspace}}` dir: `{{$result.RepoRelDir}}`\n" +
"{{end}}\n" +
"{{ range $i, $result := .Results }}" +
"### {{add $i 1}}. workspace: `{{$result.Workspace}}` dir: `{{$result.RepoRelDir}}`\n" +
"{{$result.Rendered}}\n\n" +
"---\n{{end}}" +
logTmpl))
var planSuccessUnwrappedTmpl = template.Must(template.New("").Parse(
"```diff\n" +
"{{.TerraformOutput}}\n" +
"```\n\n" + planNextSteps))
var planSuccessWrappedTmpl = template.Must(template.New("").Parse(
"<details><summary>Show Output</summary>\n\n" +
"```diff\n" +
"{{.TerraformOutput}}\n" +
"```\n\n" +
planNextSteps + "\n" +
"</details>"))
// planNextSteps are instructions appended after successful plans as to what
// to do next.
var planNextSteps = "* :arrow_forward: To **apply** this plan, comment:\n" +
" * `{{.ApplyCmd}}`\n" +
"* :put_litter_in_its_place: To **delete** this plan click [here]({{.LockURL}})\n" +
"* :repeat: To **plan** this project again, comment:\n" +
" * `{{.RePlanCmd}}`"
var applyUnwrappedSuccessTmpl = template.Must(template.New("").Parse(
"```diff\n" +
"{{.Output}}\n" +
"```"))
var applyWrappedSuccessTmpl = template.Must(template.New("").Parse(
"<details><summary>Show Output</summary>\n\n" +
"```diff\n" +
"{{.Output}}\n" +
"```\n" +
"</details>"))
var unwrappedErrTmplText = "**{{.Command}} Error**\n" +
"```\n" +
"{{.Error}}\n" +
"```"
var wrappedErrTmplText = "**{{.Command}} Error**\n" +
"<details><summary>Show Output</summary>\n\n" +
"```\n" +
"{{.Error}}\n" +
"```\n</details>"
var unwrappedErrTmpl = template.Must(template.New("").Parse(unwrappedErrTmplText))
var unwrappedErrWithLogTmpl = template.Must(template.New("").Parse(unwrappedErrTmplText + logTmpl))
var wrappedErrTmpl = template.Must(template.New("").Parse(wrappedErrTmplText))
var failureTmplText = "**{{.Command}} Failed**: {{.Failure}}"
var failureTmpl = template.Must(template.New("").Parse(failureTmplText))
var failureWithLogTmpl = template.Must(template.New("").Parse(failureTmplText + logTmpl))
var logTmpl = "{{if .Verbose}}\n<details><summary>Log</summary>\n <p>\n\n```\n{{.Log}}```\n</p></details>{{end}}\n"