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