-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathmarkdown_renderer.go
442 lines (411 loc) · 17.1 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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// 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"
"embed"
"fmt"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/runatlantis/atlantis/server/events/command"
"github.com/runatlantis/atlantis/server/events/models"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
var (
planCommandTitle = command.Plan.TitleString()
applyCommandTitle = command.Apply.TitleString()
policyCheckCommandTitle = command.PolicyCheck.TitleString()
approvePoliciesCommandTitle = command.ApprovePolicies.TitleString()
versionCommandTitle = command.Version.TitleString()
importCommandTitle = command.Import.TitleString()
stateCommandTitle = command.State.TitleString()
// maxUnwrappedLines is the maximum number of lines the Terraform output
// can be before we wrap it in an expandable template.
maxUnwrappedLines = 12
//go:embed templates/*
templatesFS embed.FS
)
// 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
disableApplyAll bool
disableApply bool
disableMarkdownFolding bool
disableRepoLocking bool
enableDiffMarkdownFormat bool
markdownTemplates *template.Template
executableName string
hideUnchangedPlanComments bool
quietPolicyChecks bool
}
// commonData is data that all responses have.
type commonData struct {
Command string
SubCommand string
Verbose bool
Log string
PlansDeleted bool
DisableApplyAll bool
DisableApply bool
DisableRepoLocking bool
EnableDiffMarkdownFormat bool
ExecutableName string
HideUnchangedPlanComments bool
QuietPolicyChecks bool
VcsRequestType string
}
// errData is data about an error response.
type errData struct {
Error string
RenderedContext string
commonData
}
// failureData is data about a failure response.
type failureData struct {
Failure string
RenderedContext string
commonData
}
type resultData struct {
Results []projectResultTmplData
commonData
}
type planResultData struct {
Results []projectResultTmplData
commonData
NumPlansWithChanges int
NumPlansWithNoChanges int
NumPlanFailures int
}
type applyResultData struct {
Results []projectResultTmplData
commonData
NumApplySuccesses int
NumApplyFailures int
NumApplyErrors int
}
type planSuccessData struct {
models.PlanSuccess
PlanSummary string
PlanWasDeleted bool
DisableApply bool
DisableRepoLocking bool
EnableDiffMarkdownFormat bool
PlanStats models.PlanSuccessStats
}
type policyCheckResultsData struct {
models.PolicyCheckResults
PreConftestOutput string
PostConftestOutput string
PolicyCheckSummary string
PolicyApprovalSummary string
PolicyCleared bool
commonData
}
type projectResultTmplData struct {
Workspace string
RepoRelDir string
ProjectName string
Rendered string
NoChanges bool
IsSuccessful bool
}
// Initialize templates
func NewMarkdownRenderer(
gitlabSupportsCommonMark bool,
disableApplyAll bool,
disableApply bool,
disableMarkdownFolding bool,
disableRepoLocking bool,
enableDiffMarkdownFormat bool,
markdownTemplateOverridesDir string,
executableName string,
hideUnchangedPlanComments bool,
quietPolicyChecks bool,
) *MarkdownRenderer {
var templates *template.Template
templates, _ = template.New("").Funcs(sprig.TxtFuncMap()).ParseFS(templatesFS, "templates/*.tmpl")
if overrides, err := templates.ParseGlob(fmt.Sprintf("%s/*.tmpl", markdownTemplateOverridesDir)); err == nil {
// doesn't override if templates directory doesn't exist
templates = overrides
}
return &MarkdownRenderer{
gitlabSupportsCommonMark: gitlabSupportsCommonMark,
disableApplyAll: disableApplyAll,
disableMarkdownFolding: disableMarkdownFolding,
disableApply: disableApply,
disableRepoLocking: disableRepoLocking,
enableDiffMarkdownFormat: enableDiffMarkdownFormat,
markdownTemplates: templates,
executableName: executableName,
hideUnchangedPlanComments: hideUnchangedPlanComments,
quietPolicyChecks: quietPolicyChecks,
}
}
// Render formats the data into a markdown string.
// nolint: interfacer
func (m *MarkdownRenderer) Render(ctx *command.Context, res command.Result, cmd PullCommand) string {
commandStr := cases.Title(language.English).String(strings.Replace(cmd.CommandName().String(), "_", " ", -1))
var vcsRequestType string
if ctx.Pull.BaseRepo.VCSHost.Type == models.Gitlab {
vcsRequestType = "Merge Request"
} else {
vcsRequestType = "Pull Request"
}
common := commonData{
Command: commandStr,
SubCommand: cmd.SubCommandName(),
Verbose: cmd.IsVerbose(),
Log: ctx.Log.GetHistory(),
PlansDeleted: res.PlansDeleted,
DisableApplyAll: m.disableApplyAll || m.disableApply,
DisableApply: m.disableApply,
DisableRepoLocking: m.disableRepoLocking,
EnableDiffMarkdownFormat: m.enableDiffMarkdownFormat,
ExecutableName: m.executableName,
HideUnchangedPlanComments: m.hideUnchangedPlanComments,
QuietPolicyChecks: m.quietPolicyChecks,
VcsRequestType: vcsRequestType,
}
templates := m.markdownTemplates
if res.Error != nil {
return m.renderTemplateTrimSpace(templates.Lookup("unwrappedErrWithLog"), errData{res.Error.Error(), "", common})
}
if res.Failure != "" {
return m.renderTemplateTrimSpace(templates.Lookup("failureWithLog"), failureData{res.Failure, "", common})
}
return m.renderProjectResults(ctx, res.ProjectResults, common)
}
func (m *MarkdownRenderer) renderProjectResults(ctx *command.Context, results []command.ProjectResult, common commonData) string {
vcsHost := ctx.Pull.BaseRepo.VCSHost.Type
var resultsTmplData []projectResultTmplData
numPlanSuccesses := 0
numPolicyCheckSuccesses := 0
numPolicyApprovalSuccesses := 0
numVersionSuccesses := 0
numPlansWithChanges := 0
numPlansWithNoChanges := 0
numApplySuccesses := 0
numApplyFailures := 0
numApplyErrors := 0
templates := m.markdownTemplates
for _, result := range results {
resultData := projectResultTmplData{
Workspace: result.Workspace,
RepoRelDir: result.RepoRelDir,
ProjectName: result.ProjectName,
IsSuccessful: result.IsSuccessful(),
}
if result.PlanSuccess != nil {
result.PlanSuccess.TerraformOutput = strings.TrimSpace(result.PlanSuccess.TerraformOutput)
data := planSuccessData{
PlanSuccess: *result.PlanSuccess,
PlanWasDeleted: common.PlansDeleted,
DisableApply: common.DisableApply,
DisableRepoLocking: common.DisableRepoLocking,
EnableDiffMarkdownFormat: common.EnableDiffMarkdownFormat,
PlanStats: result.PlanSuccess.Stats(),
}
if m.shouldUseWrappedTmpl(vcsHost, result.PlanSuccess.TerraformOutput) {
data.PlanSummary = result.PlanSuccess.Summary()
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("planSuccessWrapped"), data)
} else {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("planSuccessUnwrapped"), data)
}
resultData.NoChanges = result.PlanSuccess.NoChanges()
if result.PlanSuccess.NoChanges() {
numPlansWithNoChanges++
} else {
numPlansWithChanges++
}
numPlanSuccesses++
} else if result.PolicyCheckResults != nil && common.Command == policyCheckCommandTitle {
policyCheckResults := policyCheckResultsData{
PreConftestOutput: result.PolicyCheckResults.PreConftestOutput,
PostConftestOutput: result.PolicyCheckResults.PostConftestOutput,
PolicyCheckResults: *result.PolicyCheckResults,
PolicyCheckSummary: result.PolicyCheckResults.Summary(),
PolicyApprovalSummary: result.PolicyCheckResults.PolicySummary(),
PolicyCleared: result.PolicyCheckResults.PolicyCleared(),
commonData: common,
}
if m.shouldUseWrappedTmpl(vcsHost, result.PolicyCheckResults.CombinedOutput()) {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("policyCheckResultsWrapped"), policyCheckResults)
} else {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("policyCheckResultsUnwrapped"), policyCheckResults)
}
if result.Error == nil && result.Failure == "" {
numPolicyCheckSuccesses++
}
} else if result.PolicyCheckResults != nil && common.Command == approvePoliciesCommandTitle {
policyCheckResults := policyCheckResultsData{
PolicyCheckResults: *result.PolicyCheckResults,
PolicyCheckSummary: result.PolicyCheckResults.Summary(),
PolicyApprovalSummary: result.PolicyCheckResults.PolicySummary(),
PolicyCleared: result.PolicyCheckResults.PolicyCleared(),
commonData: common,
}
if m.shouldUseWrappedTmpl(vcsHost, result.PolicyCheckResults.CombinedOutput()) {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("policyCheckResultsWrapped"), policyCheckResults)
} else {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("policyCheckResultsUnwrapped"), policyCheckResults)
}
if result.Error == nil && result.Failure == "" {
numPolicyApprovalSuccesses++
}
} else if result.ApplySuccess != "" {
output := strings.TrimSpace(result.ApplySuccess)
if m.shouldUseWrappedTmpl(vcsHost, result.ApplySuccess) {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("applyWrappedSuccess"), struct{ Output string }{output})
} else {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("applyUnwrappedSuccess"), struct{ Output string }{output})
}
numApplySuccesses++
} else if result.VersionSuccess != "" {
output := strings.TrimSpace(result.VersionSuccess)
if m.shouldUseWrappedTmpl(vcsHost, output) {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("versionWrappedSuccess"), struct{ Output string }{output})
} else {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("versionUnwrappedSuccess"), struct{ Output string }{output})
}
numVersionSuccesses++
} else if result.ImportSuccess != nil {
result.ImportSuccess.Output = strings.TrimSpace(result.ImportSuccess.Output)
if m.shouldUseWrappedTmpl(vcsHost, result.ImportSuccess.Output) {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("importSuccessWrapped"), result.ImportSuccess)
} else {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("importSuccessUnwrapped"), result.ImportSuccess)
}
} else if result.StateRmSuccess != nil {
result.StateRmSuccess.Output = strings.TrimSpace(result.StateRmSuccess.Output)
if m.shouldUseWrappedTmpl(vcsHost, result.StateRmSuccess.Output) {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("stateRmSuccessWrapped"), result.StateRmSuccess)
} else {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("stateRmSuccessUnwrapped"), result.StateRmSuccess)
}
// Error out if no template was found, only if there are no errors or failures.
// This is because some errors and failures rely on additional context rendered by templates, but not all errors or failures.
} else if !(result.Error != nil || result.Failure != "") {
resultData.Rendered = "Found no template. This is a bug!"
}
// Render error or failure templates. Done outside of previous block so that other context can be rendered for use here.
if result.Error != nil {
tmpl := templates.Lookup("unwrappedErr")
if m.shouldUseWrappedTmpl(vcsHost, result.Error.Error()) {
tmpl = templates.Lookup("wrappedErr")
}
resultData.Rendered = m.renderTemplateTrimSpace(tmpl, errData{result.Error.Error(), resultData.Rendered, common})
if common.Command == applyCommandTitle {
numApplyErrors++
}
} else if result.Failure != "" {
resultData.Rendered = m.renderTemplateTrimSpace(templates.Lookup("failure"), failureData{result.Failure, resultData.Rendered, common})
if common.Command == applyCommandTitle {
numApplyFailures++
}
}
resultsTmplData = append(resultsTmplData, resultData)
}
var tmpl *template.Template
switch {
case len(resultsTmplData) == 1 && common.Command == planCommandTitle && numPlanSuccesses > 0:
tmpl = templates.Lookup("singleProjectPlanSuccess")
case len(resultsTmplData) == 1 && common.Command == planCommandTitle && numPlanSuccesses == 0:
tmpl = templates.Lookup("singleProjectPlanUnsuccessful")
case len(resultsTmplData) == 1 && common.Command == policyCheckCommandTitle && numPolicyCheckSuccesses > 0:
tmpl = templates.Lookup("singleProjectPlanSuccess")
case len(resultsTmplData) == 1 && common.Command == policyCheckCommandTitle && numPolicyCheckSuccesses == 0:
tmpl = templates.Lookup("singleProjectPolicyUnsuccessful")
case len(resultsTmplData) == 1 && common.Command == versionCommandTitle && numVersionSuccesses > 0:
tmpl = templates.Lookup("singleProjectVersionSuccess")
case len(resultsTmplData) == 1 && common.Command == versionCommandTitle && numVersionSuccesses == 0:
tmpl = templates.Lookup("singleProjectVersionUnsuccessful")
case len(resultsTmplData) == 1 && common.Command == applyCommandTitle:
tmpl = templates.Lookup("singleProjectApply")
case len(resultsTmplData) == 1 && common.Command == importCommandTitle:
tmpl = templates.Lookup("singleProjectImport")
case len(resultsTmplData) == 1 && common.Command == stateCommandTitle:
switch common.SubCommand {
case "rm":
tmpl = templates.Lookup("singleProjectStateRm")
default:
return fmt.Sprintf("no template matched–this is a bug: command=%s, subcommand=%s", common.Command, common.SubCommand)
}
case common.Command == planCommandTitle:
tmpl = templates.Lookup("multiProjectPlan")
case common.Command == policyCheckCommandTitle:
if numPolicyCheckSuccesses == len(results) {
tmpl = templates.Lookup("multiProjectPolicy")
} else {
tmpl = templates.Lookup("multiProjectPolicyUnsuccessful")
}
case common.Command == approvePoliciesCommandTitle:
if numPolicyApprovalSuccesses == len(results) {
tmpl = templates.Lookup("approveAllProjects")
} else {
tmpl = templates.Lookup("multiProjectPolicyUnsuccessful")
}
case common.Command == applyCommandTitle:
tmpl = templates.Lookup("multiProjectApply")
case common.Command == versionCommandTitle:
tmpl = templates.Lookup("multiProjectVersion")
case common.Command == importCommandTitle:
tmpl = templates.Lookup("multiProjectImport")
case common.Command == stateCommandTitle:
switch common.SubCommand {
case "rm":
tmpl = templates.Lookup("multiProjectStateRm")
default:
return fmt.Sprintf("no template matched–this is a bug: command=%s, subcommand=%s", common.Command, common.SubCommand)
}
default:
return fmt.Sprintf("no template matched–this is a bug: command=%s", common.Command)
}
switch {
case common.Command == planCommandTitle:
numPlanFailures := len(results) - numPlanSuccesses
return m.renderTemplateTrimSpace(tmpl, planResultData{resultsTmplData, common, numPlansWithChanges, numPlansWithNoChanges, numPlanFailures})
case common.Command == applyCommandTitle:
return m.renderTemplateTrimSpace(tmpl, applyResultData{resultsTmplData, common, numApplySuccesses, numApplyFailures, numApplyErrors})
}
return m.renderTemplateTrimSpace(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 {
if m.disableMarkdownFolding {
return false
}
// 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) renderTemplateTrimSpace(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 strings.TrimSpace(buf.String())
}