-
Notifications
You must be signed in to change notification settings - Fork 582
/
main.go
424 lines (344 loc) · 15.2 KB
/
main.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
package generator
import (
"bytes"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/SAP/jenkins-library/pkg/config"
"github.com/SAP/jenkins-library/pkg/piperutils"
"github.com/ghodss/yaml"
)
// DocuHelperData is used to transport the needed parameters and functions from the step generator to the docu generation.
type DocuHelperData struct {
DocTemplatePath string
OpenDocTemplateFile func(d string) (io.ReadCloser, error)
DocFileWriter func(f string, d []byte, p os.FileMode) error
OpenFile func(s string) (io.ReadCloser, error)
}
var stepParameterNames []string
var includeAzure bool
func readStepConfiguration(stepMetadata config.StepData, customDefaultFiles []string, docuHelperData DocuHelperData) config.StepConfig {
filters := stepMetadata.GetParameterFilters()
filters.All = append(filters.All, "collectTelemetryData")
filters.General = append(filters.General, "collectTelemetryData")
filters.Parameters = append(filters.Parameters, "collectTelemetryData")
defaultFiles := []io.ReadCloser{}
for _, projectDefaultFile := range customDefaultFiles {
fc, _ := docuHelperData.OpenFile(projectDefaultFile)
defer fc.Close()
defaultFiles = append(defaultFiles, fc)
}
configuration := config.Config{}
stepConfiguration, err := configuration.GetStepConfig(
map[string]interface{}{},
"",
nil,
defaultFiles,
false,
filters,
stepMetadata,
map[string]interface{}{},
"",
stepMetadata.Metadata.Name,
)
checkError(err)
return stepConfiguration
}
// GenerateStepDocumentation generates step coding based on step configuration provided in yaml files
func GenerateStepDocumentation(metadataFiles []string, customDefaultFiles []string, docuHelperData DocuHelperData, azure bool) error {
includeAzure = azure
for key := range metadataFiles {
stepMetadata := readStepMetadata(metadataFiles[key], docuHelperData)
adjustDefaultValues(&stepMetadata)
stepConfiguration := readStepConfiguration(stepMetadata, customDefaultFiles, docuHelperData)
applyCustomDefaultValues(&stepMetadata, stepConfiguration)
adjustMandatoryFlags(&stepMetadata)
fmt.Print(" Generate documentation.. ")
if err := generateStepDocumentation(stepMetadata, docuHelperData); err != nil {
fmt.Println("")
fmt.Println(err)
} else {
fmt.Println("completed")
}
}
return nil
}
// generates the step documentation and replaces the template with the generated documentation
func generateStepDocumentation(stepData config.StepData, docuHelperData DocuHelperData) error {
//create the file path for the template and open it.
docTemplateFilePath := fmt.Sprintf("%v%v.md", docuHelperData.DocTemplatePath, stepData.Metadata.Name)
docTemplate, err := docuHelperData.OpenDocTemplateFile(docTemplateFilePath)
if docTemplate != nil {
defer docTemplate.Close()
}
// check if there is an error during opening the template (true : skip docu generation for this meta data file)
if err != nil {
return fmt.Errorf("error occurred: %v", err)
}
content := readAndAdjustTemplate(docTemplate)
if len(content) <= 0 {
return fmt.Errorf("error occurred: no content inside of the template")
}
// binding of functions and placeholder
tmpl, err := template.New("doc").Funcs(template.FuncMap{
"StepName": createStepName,
"Description": createDescriptionSection,
"Parameters": createParametersSection,
}).Parse(content)
checkError(err)
// add secrets, context defaults to the step parameters
handleStepParameters(&stepData)
// write executed template data to the previously opened file
var docContent bytes.Buffer
err = tmpl.Execute(&docContent, &stepData)
checkError(err)
// overwrite existing file
err = docuHelperData.DocFileWriter(docTemplateFilePath, docContent.Bytes(), 644)
checkError(err)
return nil
}
func readContextInformation(contextDetailsPath string, contextDetails *config.StepData) {
contextDetailsFile, err := os.Open(contextDetailsPath)
checkError(err)
defer contextDetailsFile.Close()
err = contextDetails.ReadPipelineStepData(contextDetailsFile)
checkError(err)
}
func getContainerParameters(container config.Container, sidecar bool) map[string]interface{} {
containerParams := map[string]interface{}{}
if len(container.Command) > 0 {
containerParams[ifThenElse(sidecar, "sidecarCommand", "containerCommand")] = container.Command[0]
}
if len(container.EnvVars) > 0 {
containerParams[ifThenElse(sidecar, "sidecarEnvVars", "dockerEnvVars")] = config.EnvVarsAsMap(container.EnvVars)
}
containerParams[ifThenElse(sidecar, "sidecarImage", "dockerImage")] = container.Image
containerParams[ifThenElse(sidecar, "sidecarPullImage", "dockerPullImage")] = container.ImagePullPolicy != "Never"
if len(container.Name) > 0 {
containerParams[ifThenElse(sidecar, "sidecarName", "containerName")] = container.Name
containerParams["dockerName"] = container.Name
}
if len(container.Options) > 0 {
containerParams[ifThenElse(sidecar, "sidecarOptions", "dockerOptions")] = container.Options
}
if len(container.WorkingDir) > 0 {
containerParams[ifThenElse(sidecar, "sidecarWorkspace", "dockerWorkspace")] = container.WorkingDir
}
if sidecar {
if len(container.ReadyCommand) > 0 {
containerParams["sidecarReadyCommand"] = container.ReadyCommand
}
} else {
if len(container.Shell) > 0 {
containerParams["containerShell"] = container.Shell
}
}
//ToDo? add dockerVolumeBind, sidecarVolumeBind -> so far not part of config.Container
return containerParams
}
func handleStepParameters(stepData *config.StepData) {
stepParameterNames = stepData.GetParameterFilters().All
//add general options like script, verbose, etc.
//ToDo: add to context.yaml
appendGeneralOptionsToParameters(stepData)
//consolidate conditional parameters:
//- remove duplicate parameter entries
//- combine defaults (consider conditions)
consolidateConditionalParameters(stepData)
//get the context defaults
appendContextParameters(stepData)
//consolidate context defaults:
//- combine defaults (consider conditions)
consolidateContextDefaults(stepData)
setDefaultAndPossisbleValues(stepData)
}
func setDefaultAndPossisbleValues(stepData *config.StepData) {
for k, param := range stepData.Spec.Inputs.Parameters {
//fill default if not set
if param.Default == nil {
switch param.Type {
case "bool":
param.Default = false
case "int":
param.Default = 0
}
}
//add possible values where known for certain types
switch param.Type {
case "bool":
if param.PossibleValues == nil {
param.PossibleValues = []interface{}{true, false}
}
}
stepData.Spec.Inputs.Parameters[k] = param
}
}
func appendGeneralOptionsToParameters(stepData *config.StepData) {
script := config.StepParameters{
Name: "script", Type: "Jenkins Script", Mandatory: true,
Description: "The common script environment of the Jenkinsfile running. Typically the reference to the script calling the pipeline step is provided with the `this` parameter, as in `script: this`. This allows the function to access the `commonPipelineEnvironment` for retrieving, e.g. configuration parameters.",
}
verbose := config.StepParameters{
Name: "verbose", Type: "bool", Mandatory: false, Default: false, Scope: []string{"PARAMETERS", "GENERAL", "STEPS", "STAGES"},
Description: "verbose output",
}
stepData.Spec.Inputs.Parameters = append(stepData.Spec.Inputs.Parameters, script, verbose)
}
// GenerateStepDocumentation generates pipeline stage documentation based on pipeline configuration provided in a yaml file
func GenerateStageDocumentation(stageMetadataPath, stageTargetPath, relativeStepsPath string, utils piperutils.FileUtils) error {
if len(stageTargetPath) == 0 {
return fmt.Errorf("stageTargetPath cannot be empty")
}
if len(stageMetadataPath) == 0 {
return fmt.Errorf("stageMetadataPath cannot be empty")
}
if err := utils.MkdirAll(stageTargetPath, 0777); err != nil {
return fmt.Errorf("failed to create directory '%v': %w", stageTargetPath, err)
}
stageMetadataContent, err := utils.FileRead(stageMetadataPath)
if err != nil {
return fmt.Errorf("failed to read stage metadata file '%v': %w", stageMetadataPath, err)
}
stageRunConfig := config.RunConfigV1{}
err = yaml.Unmarshal(stageMetadataContent, &stageRunConfig.PipelineConfig)
if err != nil {
return fmt.Errorf("format of configuration is invalid %q: %w", stageMetadataContent, err)
}
err = createPipelineDocumentation(&stageRunConfig, stageTargetPath, relativeStepsPath, utils)
if err != nil {
return fmt.Errorf("failed to create pipeline documentation: %w", err)
}
return nil
}
func createPipelineDocumentation(stageRunConfig *config.RunConfigV1, stageTargetPath, relativeStepsPath string, utils piperutils.FileUtils) error {
if err := createPipelineOverviewDocumentation(stageRunConfig, stageTargetPath, utils); err != nil {
return fmt.Errorf("failed to create pipeline overview: %w", err)
}
if err := createPipelineStageDocumentation(stageRunConfig, stageTargetPath, relativeStepsPath, utils); err != nil {
return fmt.Errorf("failed to create pipeline stage details: %w", err)
}
return nil
}
func createPipelineOverviewDocumentation(stageRunConfig *config.RunConfigV1, stageTargetPath string, utils piperutils.FileUtils) error {
overviewFileName := "overview.md"
overviewDoc := fmt.Sprintf("# %v\n\n", stageRunConfig.PipelineConfig.Metadata.DisplayName)
overviewDoc += fmt.Sprintf("%v\n\n", stageRunConfig.PipelineConfig.Metadata.Description)
overviewDoc += fmt.Sprintf("The %v comprises following stages\n\n", stageRunConfig.PipelineConfig.Metadata.DisplayName)
for _, stage := range stageRunConfig.PipelineConfig.Spec.Stages {
stageFilePath := filepath.Join(stageTargetPath, fmt.Sprintf("%v.md", stage.Name))
overviewDoc += fmt.Sprintf("* [%v Stage](%v)\n", stage.DisplayName, stageFilePath)
}
overviewFilePath := filepath.Join(stageTargetPath, overviewFileName)
fmt.Println("writing file", overviewFilePath)
return utils.FileWrite(overviewFilePath, []byte(overviewDoc), 0666)
}
const stepConditionDetails = `!!! note "Step condition details"
There are currently several conditions which can be checked.<br />**Important: It will be sufficient that any one condition per step is met.**
* ` + "`" + `config` + "`" + `: Checks if a configuration parameter has a defined value.
* ` + "`" + `config key` + "`" + `: Checks if a defined configuration parameter is set.
* ` + "`" + `file pattern` + "`" + `: Checks if files according a defined pattern exist in the project.
* ` + "`" + `file pattern from config` + "`" + `: Checks if files according a pattern defined in the custom configuration exist in the project.
* ` + "`" + `npm script` + "`" + `: Checks if a npm script exists in one of the package.json files in the repositories.
`
const overrulingStepActivation = `!!! note "Overruling step activation conditions"
It is possible to overrule the automatically detected step activation status.
* In case a step will be **active** you can add to your stage configuration ` + "`" + `<stepName>: false` + "`" + ` to explicitly **deactivate** the step.
* In case a step will be **inactive** you can add to your stage configuration ` + "`" + `<stepName>: true` + "`" + ` to explicitly **activate** the step.
`
func createPipelineStageDocumentation(stageRunConfig *config.RunConfigV1, stageTargetPath, relativeStepsPath string, utils piperutils.FileUtils) error {
for _, stage := range stageRunConfig.PipelineConfig.Spec.Stages {
stageDoc := fmt.Sprintf("# %v\n\n", stage.DisplayName)
stageDoc += fmt.Sprintf("%v\n\n", stage.Description)
if len(stage.Steps) > 0 {
stageDoc += "## Stage Content\n\nThis stage comprises following steps which are activated depending on your use-case/configuration:\n\n"
for i, step := range stage.Steps {
if i == 0 {
stageDoc += "| step | step description |\n"
stageDoc += "| ---- | ---------------- |\n"
}
orchestratorBadges := ""
for _, orchestrator := range step.Orchestrators {
orchestratorBadges += getBadge(orchestrator) + " "
}
stageDoc += fmt.Sprintf("| [%v](%v/%v.md) | %v%v |\n", step.Name, relativeStepsPath, step.Name, orchestratorBadges, step.Description)
}
stageDoc += "\n"
stageDoc += "## Stage & Step Activation\n\nThis stage will be active in case one of following conditions are met:\n\n"
stageDoc += "* One of the steps is explicitly activated by using `<stepName>: true` in the stage configuration\n"
stageDoc += "* At least one of the step conditions is met and steps are not explicitly deactivated by using `<stepName>: false` in the stage configuration\n\n"
stageDoc += stepConditionDetails
stageDoc += overrulingStepActivation
stageDoc += "Following conditions apply for activation of steps contained in the stage:\n\n"
stageDoc += "| step | active if one of following conditions is met |\n"
stageDoc += "| ---- | -------------------------------------------- |\n"
// add step condition details
for _, step := range stage.Steps {
stageDoc += fmt.Sprintf("| [%v](%v/%v.md) | %v |\n", step.Name, relativeStepsPath, step.Name, getStepConditionDetails(step))
}
}
stageFilePath := filepath.Join(stageTargetPath, fmt.Sprintf("%v.md", stage.Name))
fmt.Println("writing file", stageFilePath)
if err := utils.FileWrite(stageFilePath, []byte(stageDoc), 0666); err != nil {
return fmt.Errorf("failed to write stage file '%v': %w", stageFilePath, err)
}
}
return nil
}
func getBadge(orchestrator string) string {
orchestratorOnly := piperutils.Title(strings.ToLower(orchestrator)) + " only"
urlPath := &url.URL{Path: orchestratorOnly}
orchestratorOnlyString := urlPath.String()
return fmt.Sprintf("[![%v](https://img.shields.io/badge/-%v-yellowgreen)](#)", orchestratorOnly, orchestratorOnlyString)
}
func getStepConditionDetails(step config.Step) string {
stepConditions := ""
if step.Conditions == nil || len(step.Conditions) == 0 {
return "**active** by default - deactivate explicitly"
}
if len(step.Orchestrators) > 0 {
orchestratorBadges := ""
for _, orchestrator := range step.Orchestrators {
orchestratorBadges += getBadge(orchestrator) + " "
}
stepConditions = orchestratorBadges + "<br />"
}
for _, condition := range step.Conditions {
if condition.Config != nil && len(condition.Config) > 0 {
stepConditions += "<i>config:</i><ul>"
for param, activationValues := range condition.Config {
for _, activationValue := range activationValues {
stepConditions += fmt.Sprintf("<li>`%v`: `%v`</li>", param, activationValue)
}
// config condition only covers first entry
break
}
stepConditions += "</ul>"
continue
}
if len(condition.ConfigKey) > 0 {
stepConditions += fmt.Sprintf("<i>config key:</i> `%v`<br />", condition.ConfigKey)
continue
}
if len(condition.FilePattern) > 0 {
stepConditions += fmt.Sprintf("<i>file pattern:</i> `%v`<br />", condition.FilePattern)
continue
}
if len(condition.FilePatternFromConfig) > 0 {
stepConditions += fmt.Sprintf("<i>file pattern from config:</i> `%v`<br />", condition.FilePatternFromConfig)
continue
}
if len(condition.NpmScript) > 0 {
stepConditions += fmt.Sprintf("<i>npm script:</i> `%v`<br />", condition.NpmScript)
continue
}
if condition.Inactive {
stepConditions += "**inactive** by default - activate explicitly"
continue
}
}
return stepConditions
}