github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/generator/helper/testdata/TestProcessMetaFiles/custom_step_code_generated.golden (about) 1 // Code generated by piper's step-generator. DO NOT EDIT. 2 3 package cmd 4 5 import ( 6 "fmt" 7 "os" 8 "reflect" 9 "strings" 10 "path/filepath" 11 "time" 12 13 piperOsCmd "github.com/ouraigua/jenkins-library/cmd" 14 "github.com/SAP/jenkins-library/pkg/config" 15 "github.com/SAP/jenkins-library/pkg/log" 16 "github.com/bmatcuk/doublestar" 17 "github.com/SAP/jenkins-library/pkg/gcs" 18 "github.com/SAP/jenkins-library/pkg/piperenv" 19 "github.com/SAP/jenkins-library/pkg/telemetry" 20 "github.com/SAP/jenkins-library/pkg/splunk" 21 "github.com/SAP/jenkins-library/pkg/validation" 22 "github.com/spf13/cobra" 23 ) 24 25 type testStepOptions struct { 26 Param0 string `json:"param0,omitempty"` 27 Param1 string `json:"param1,omitempty" validate:"possible-values=value1 value2 value3"` 28 Param2 string `json:"param2,omitempty" validate:"required_if=Param1 value1"` 29 Param3 string `json:"param3,omitempty" validate:"possible-values=value1 value2 value3,required_if=Param1 value1 Param2 value2"` 30 } 31 32 33 type testStepReports struct { 34 } 35 36 func (p *testStepReports) persist(stepConfig testStepOptions, gcpJsonKeyFilePath string, gcsBucketId string, gcsFolderPath string, gcsSubFolder string) { 37 if gcsBucketId == "" { 38 log.Entry().Info("persisting reports to GCS is disabled, because gcsBucketId is empty") 39 return 40 } 41 log.Entry().Info("Uploading reports to Google Cloud Storage...") 42 content := []gcs.ReportOutputParam{ 43 {FilePattern: "test-report_*.json", ParamRef: "", StepResultType: ""}, 44 {FilePattern: "report1", ParamRef: "", StepResultType: "general"}, 45 } 46 envVars := []gcs.EnvVar{ 47 {Name: "GOOGLE_APPLICATION_CREDENTIALS", Value: gcpJsonKeyFilePath, Modified: false}, 48 } 49 gcsClient, err := gcs.NewClient(gcs.WithEnvVars(envVars)) 50 if err != nil { 51 log.Entry().Errorf("creation of GCS client failed: %v", err) 52 return 53 } 54 defer gcsClient.Close() 55 structVal := reflect.ValueOf(&stepConfig).Elem() 56 inputParameters := map[string]string{} 57 for i := 0; i < structVal.NumField(); i++ { 58 field := structVal.Type().Field(i) 59 if field.Type.String() == "string" { 60 paramName := strings.Split(field.Tag.Get("json"), ",") 61 paramValue, _ := structVal.Field(i).Interface().(string) 62 inputParameters[paramName[0]] = paramValue 63 } 64 } 65 if err := gcs.PersistReportsToGCS(gcsClient, content, inputParameters, gcsFolderPath, gcsBucketId, gcsSubFolder, doublestar.Glob, os.Stat); err != nil { 66 log.Entry().Errorf("failed to persist reports: %v", err) 67 } 68 } 69 70 type testStepCommonPipelineEnvironment struct { 71 artifactVersion string 72 git struct { 73 commitID string 74 headCommitID string 75 branch string 76 } 77 custom struct { 78 customList []string 79 } 80 } 81 82 func (p *testStepCommonPipelineEnvironment) persist(path, resourceName string) { 83 content := []struct{ 84 category string 85 name string 86 value interface{} 87 }{ 88 {category: "", name: "artifactVersion", value: p.artifactVersion}, 89 {category: "git", name: "commitId", value: p.git.commitID}, 90 {category: "git", name: "headCommitId", value: p.git.headCommitID}, 91 {category: "git", name: "branch", value: p.git.branch}, 92 {category: "custom", name: "customList", value: p.custom.customList}, 93 } 94 95 errCount := 0 96 for _, param := range content { 97 err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(param.category, param.name), param.value) 98 if err != nil { 99 log.Entry().WithError(err).Error("Error persisting piper environment.") 100 errCount++ 101 } 102 } 103 if errCount > 0 { 104 log.Entry().Error("failed to persist Piper environment") 105 } 106 } 107 108 type testStepInfluxTest struct { 109 m1 struct { 110 fields struct { 111 f1 string 112 } 113 tags struct { 114 t1 string 115 } 116 } 117 } 118 119 func (i *testStepInfluxTest) persist(path, resourceName string) { 120 measurementContent := []struct{ 121 measurement string 122 valType string 123 name string 124 value interface{} 125 }{ 126 {valType: config.InfluxField, measurement: "m1" , name: "f1", value: i.m1.fields.f1}, 127 {valType: config.InfluxTag, measurement: "m1" , name: "t1", value: i.m1.tags.t1}, 128 } 129 130 errCount := 0 131 for _, metric := range measurementContent { 132 err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(metric.measurement, fmt.Sprintf("%vs", metric.valType), metric.name), metric.value) 133 if err != nil { 134 log.Entry().WithError(err).Error("Error persisting influx environment.") 135 errCount++ 136 } 137 } 138 if errCount > 0 { 139 log.Entry().Error("failed to persist Influx environment") 140 } 141 } 142 143 144 // TestStepCommand Test description 145 func TestStepCommand() *cobra.Command { 146 const STEP_NAME = "testStep" 147 148 metadata := testStepMetadata() 149 var stepConfig testStepOptions 150 var startTime time.Time 151 var reports testStepReports 152 var commonPipelineEnvironment testStepCommonPipelineEnvironment 153 var influxTest testStepInfluxTest 154 var logCollector *log.CollectorHook 155 var splunkClient *splunk.Splunk 156 telemetryClient := &telemetry.Telemetry{} 157 158 var createTestStepCmd = &cobra.Command{ 159 Use: STEP_NAME, 160 Short: "Test description", 161 Long: `Long Test description`, 162 PreRunE: func(cmd *cobra.Command, _ []string) error { 163 startTime = time.Now() 164 log.SetStepName(STEP_NAME) 165 log.SetVerbose(piperOsCmd.GeneralConfig.Verbose) 166 167 piperOsCmd.GeneralConfig.GitHubAccessTokens = piperOsCmd.ResolveAccessTokens(piperOsCmd.GeneralConfig.GitHubTokens) 168 169 path, _ := os.Getwd() 170 fatalHook := &log.FatalHook{CorrelationID: piperOsCmd.GeneralConfig.CorrelationID, Path: path} 171 log.RegisterHook(fatalHook) 172 173 err := piperOsCmd.PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile) 174 if err != nil { 175 log.SetErrorCategory(log.ErrorConfiguration) 176 return err 177 } 178 179 if len(piperOsCmd.GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 { 180 sentryHook := log.NewSentryHook(piperOsCmd.GeneralConfig.HookConfig.SentryConfig.Dsn, piperOsCmd.GeneralConfig.CorrelationID) 181 log.RegisterHook(&sentryHook) 182 } 183 184 if len(piperOsCmd.GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { 185 splunkClient = &splunk.Splunk{} 186 logCollector = &log.CollectorHook{CorrelationID: piperOsCmd.GeneralConfig.CorrelationID} 187 log.RegisterHook(logCollector) 188 } 189 190 if err = log.RegisterANSHookIfConfigured(piperOsCmd.GeneralConfig.CorrelationID); err != nil { 191 log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook") 192 } 193 194 validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages()) 195 if err != nil { 196 return err 197 } 198 if err = validation.ValidateStruct(stepConfig); err != nil { 199 log.SetErrorCategory(log.ErrorConfiguration) 200 return err 201 } 202 203 return nil 204 }, 205 Run: func(_ *cobra.Command, _ []string) { 206 stepTelemetryData := telemetry.CustomData{} 207 stepTelemetryData.ErrorCode = "1" 208 handler := func() { 209 reports.persist(stepConfig,piperOsCmd.GeneralConfig.GCPJsonKeyFilePath,piperOsCmd.GeneralConfig.GCSBucketId,piperOsCmd.GeneralConfig.GCSFolderPath,piperOsCmd.GeneralConfig.GCSSubFolder) 210 commonPipelineEnvironment.persist(piperOsCmd.GeneralConfig.EnvRootPath, "commonPipelineEnvironment") 211 influxTest.persist(piperOsCmd.GeneralConfig.EnvRootPath, "influxTest") 212 config.RemoveVaultSecretFiles() 213 stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds()) 214 stepTelemetryData.ErrorCategory = log.GetErrorCategory().String() 215 stepTelemetryData.PiperCommitHash = piperOsCmd.GitCommit 216 telemetryClient.SetData(&stepTelemetryData) 217 telemetryClient.Send() 218 if len(piperOsCmd.GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { 219 splunkClient.Initialize(piperOsCmd.GeneralConfig.CorrelationID, 220 piperOsCmd.GeneralConfig.HookConfig.SplunkConfig.Dsn, 221 piperOsCmd.GeneralConfig.HookConfig.SplunkConfig.Token, 222 piperOsCmd.GeneralConfig.HookConfig.SplunkConfig.Index, 223 piperOsCmd.GeneralConfig.HookConfig.SplunkConfig.SendLogs) 224 splunkClient.Send(telemetryClient.GetData(), logCollector) 225 } 226 if len(piperOsCmd.GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 { 227 splunkClient.Initialize(piperOsCmd.GeneralConfig.CorrelationID, 228 piperOsCmd.GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint, 229 piperOsCmd.GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken, 230 piperOsCmd.GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex, 231 piperOsCmd.GeneralConfig.HookConfig.SplunkConfig.SendLogs) 232 splunkClient.Send(telemetryClient.GetData(), logCollector) 233 } 234 } 235 log.DeferExitHandler(handler) 236 defer handler() 237 telemetryClient.Initialize(piperOsCmd.GeneralConfig.NoTelemetry, STEP_NAME) 238 testStep(stepConfig, &stepTelemetryData, &commonPipelineEnvironment, &influxTest) 239 stepTelemetryData.ErrorCode = "0" 240 log.Entry().Info("SUCCESS") 241 }, 242 } 243 244 addTestStepFlags(createTestStepCmd, &stepConfig) 245 return createTestStepCmd 246 } 247 248 func addTestStepFlags(cmd *cobra.Command, stepConfig *testStepOptions) { 249 cmd.Flags().StringVar(&stepConfig.Param0, "param0", `val0`, "param0 description") 250 cmd.Flags().StringVar(&stepConfig.Param1, "param1", os.Getenv("PIPER_param1"), "param1 description") 251 cmd.Flags().StringVar(&stepConfig.Param2, "param2", os.Getenv("PIPER_param2"), "param2 description") 252 cmd.Flags().StringVar(&stepConfig.Param3, "param3", os.Getenv("PIPER_param3"), "param3 description") 253 254 cmd.MarkFlagRequired("param0") 255 cmd.Flags().MarkDeprecated("param1", "use param3 instead") 256 } 257 258 // retrieve step metadata 259 func testStepMetadata() config.StepData { 260 var theMetaData = config.StepData{ 261 Metadata: config.StepMetadata{ 262 Name: "testStep", 263 Aliases: []config.Alias{{Name: "testStepAlias", Deprecated: true},}, 264 Description: "Test description", 265 }, 266 Spec: config.StepSpec{ 267 Inputs: config.StepInputs{ 268 Resources: []config.StepResources{ 269 {Name: "stashName",Type: "stash", 270 }, 271 }, 272 Parameters: []config.StepParameters{ 273 { 274 Name: "param0", 275 ResourceRef: []config.ResourceReference{}, 276 Scope: []string{"GENERAL","PARAMETERS",}, 277 Type: "string", 278 Mandatory: true, 279 Aliases: []config.Alias{{Name: "oldparam0"},}, 280 Default: `val0`, 281 }, 282 { 283 Name: "param1", 284 ResourceRef: []config.ResourceReference{}, 285 Scope: []string{"PARAMETERS",}, 286 Type: "string", 287 Mandatory: false, 288 Aliases: []config.Alias{{Name: "oldparam1", Deprecated: true},}, 289 Default: os.Getenv("PIPER_param1"), 290 DeprecationMessage: "use param3 instead", 291 }, 292 { 293 Name: "param2", 294 ResourceRef: []config.ResourceReference{}, 295 Scope: []string{"PARAMETERS",}, 296 Type: "string", 297 Mandatory: false, 298 Aliases: []config.Alias{}, 299 Default: os.Getenv("PIPER_param2"), 300 }, 301 { 302 Name: "param3", 303 ResourceRef: []config.ResourceReference{}, 304 Scope: []string{"PARAMETERS",}, 305 Type: "string", 306 Mandatory: false, 307 Aliases: []config.Alias{}, 308 Default: os.Getenv("PIPER_param3"), 309 }, 310 }, 311 }, 312 Outputs: config.StepOutputs{ 313 Resources: []config.StepResources{ 314 { 315 Name: "reports", 316 Type: "reports", 317 Parameters: []map[string]interface{}{ 318 {"filePattern": "test-report_*.json","subFolder": "sonarExecuteScan",}, 319 {"filePattern": "report1","type": "general",}, 320 }, 321 }, 322 { 323 Name: "commonPipelineEnvironment", 324 Type: "piperEnvironment", 325 Parameters: []map[string]interface{}{ 326 {"name": "artifactVersion",}, 327 {"name": "git/commitId",}, 328 {"name": "git/headCommitId",}, 329 {"name": "git/branch",}, 330 {"name": "custom/customList","type": "[]string",}, 331 }, 332 }, 333 { 334 Name: "influxTest", 335 Type: "influx", 336 Parameters: []map[string]interface{}{ 337 {"name": "m1","fields": []map[string]string{ {"name": "f1"}, },"tags": []map[string]string{ {"name": "t1"}, },}, 338 }, 339 }, 340 }, 341 }, 342 }, 343 } 344 return theMetaData 345 }