github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/cmd/isChangeInDevelopment_generated.go (about)

     1  // Code generated by piper's step-generator. DO NOT EDIT.
     2  
     3  package cmd
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  	"path/filepath"
     9  	"time"
    10  
    11  	"github.com/SAP/jenkins-library/pkg/config"
    12  	"github.com/SAP/jenkins-library/pkg/log"
    13  	"github.com/SAP/jenkins-library/pkg/piperenv"
    14  	"github.com/SAP/jenkins-library/pkg/splunk"
    15  	"github.com/SAP/jenkins-library/pkg/telemetry"
    16  	"github.com/SAP/jenkins-library/pkg/validation"
    17  	"github.com/spf13/cobra"
    18  )
    19  
    20  type isChangeInDevelopmentOptions struct {
    21  	Endpoint                       string   `json:"endpoint,omitempty"`
    22  	Username                       string   `json:"username,omitempty"`
    23  	Password                       string   `json:"password,omitempty"`
    24  	ChangeDocumentID               string   `json:"changeDocumentId,omitempty"`
    25  	FailIfStatusIsNotInDevelopment bool     `json:"failIfStatusIsNotInDevelopment,omitempty"`
    26  	CmClientOpts                   []string `json:"cmClientOpts,omitempty"`
    27  }
    28  
    29  type isChangeInDevelopmentCommonPipelineEnvironment struct {
    30  	custom struct {
    31  		isChangeInDevelopment bool
    32  	}
    33  }
    34  
    35  func (p *isChangeInDevelopmentCommonPipelineEnvironment) persist(path, resourceName string) {
    36  	content := []struct {
    37  		category string
    38  		name     string
    39  		value    interface{}
    40  	}{
    41  		{category: "custom", name: "isChangeInDevelopment", value: p.custom.isChangeInDevelopment},
    42  	}
    43  
    44  	errCount := 0
    45  	for _, param := range content {
    46  		err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(param.category, param.name), param.value)
    47  		if err != nil {
    48  			log.Entry().WithError(err).Error("Error persisting piper environment.")
    49  			errCount++
    50  		}
    51  	}
    52  	if errCount > 0 {
    53  		log.Entry().Error("failed to persist Piper environment")
    54  	}
    55  }
    56  
    57  // IsChangeInDevelopmentCommand This step checks if a certain change is in status 'in development'
    58  func IsChangeInDevelopmentCommand() *cobra.Command {
    59  	const STEP_NAME = "isChangeInDevelopment"
    60  
    61  	metadata := isChangeInDevelopmentMetadata()
    62  	var stepConfig isChangeInDevelopmentOptions
    63  	var startTime time.Time
    64  	var commonPipelineEnvironment isChangeInDevelopmentCommonPipelineEnvironment
    65  	var logCollector *log.CollectorHook
    66  	var splunkClient *splunk.Splunk
    67  	telemetryClient := &telemetry.Telemetry{}
    68  
    69  	var createIsChangeInDevelopmentCmd = &cobra.Command{
    70  		Use:   STEP_NAME,
    71  		Short: "This step checks if a certain change is in status 'in development'",
    72  		Long:  `This step checks if a certain change is in status 'in development'`,
    73  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    74  			startTime = time.Now()
    75  			log.SetStepName(STEP_NAME)
    76  			log.SetVerbose(GeneralConfig.Verbose)
    77  
    78  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    79  
    80  			path, _ := os.Getwd()
    81  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    82  			log.RegisterHook(fatalHook)
    83  
    84  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    85  			if err != nil {
    86  				log.SetErrorCategory(log.ErrorConfiguration)
    87  				return err
    88  			}
    89  			log.RegisterSecret(stepConfig.Username)
    90  			log.RegisterSecret(stepConfig.Password)
    91  
    92  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    93  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    94  				log.RegisterHook(&sentryHook)
    95  			}
    96  
    97  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    98  				splunkClient = &splunk.Splunk{}
    99  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   100  				log.RegisterHook(logCollector)
   101  			}
   102  
   103  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
   104  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
   105  			}
   106  
   107  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   108  			if err != nil {
   109  				return err
   110  			}
   111  			if err = validation.ValidateStruct(stepConfig); err != nil {
   112  				log.SetErrorCategory(log.ErrorConfiguration)
   113  				return err
   114  			}
   115  
   116  			return nil
   117  		},
   118  		Run: func(_ *cobra.Command, _ []string) {
   119  			stepTelemetryData := telemetry.CustomData{}
   120  			stepTelemetryData.ErrorCode = "1"
   121  			handler := func() {
   122  				commonPipelineEnvironment.persist(GeneralConfig.EnvRootPath, "commonPipelineEnvironment")
   123  				config.RemoveVaultSecretFiles()
   124  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   125  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   126  				stepTelemetryData.PiperCommitHash = GitCommit
   127  				telemetryClient.SetData(&stepTelemetryData)
   128  				telemetryClient.Send()
   129  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   130  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   131  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   132  						GeneralConfig.HookConfig.SplunkConfig.Token,
   133  						GeneralConfig.HookConfig.SplunkConfig.Index,
   134  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   135  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   136  				}
   137  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   138  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   139  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   140  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   141  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   142  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   143  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   144  				}
   145  			}
   146  			log.DeferExitHandler(handler)
   147  			defer handler()
   148  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   149  			isChangeInDevelopment(stepConfig, &stepTelemetryData, &commonPipelineEnvironment)
   150  			stepTelemetryData.ErrorCode = "0"
   151  			log.Entry().Info("SUCCESS")
   152  		},
   153  	}
   154  
   155  	addIsChangeInDevelopmentFlags(createIsChangeInDevelopmentCmd, &stepConfig)
   156  	return createIsChangeInDevelopmentCmd
   157  }
   158  
   159  func addIsChangeInDevelopmentFlags(cmd *cobra.Command, stepConfig *isChangeInDevelopmentOptions) {
   160  	cmd.Flags().StringVar(&stepConfig.Endpoint, "endpoint", os.Getenv("PIPER_endpoint"), "The service endpoint")
   161  	cmd.Flags().StringVar(&stepConfig.Username, "username", os.Getenv("PIPER_username"), "Service user to authenticate against the ABAP backend")
   162  	cmd.Flags().StringVar(&stepConfig.Password, "password", os.Getenv("PIPER_password"), "Service user password to authenticate against the ABAP backend")
   163  	cmd.Flags().StringVar(&stepConfig.ChangeDocumentID, "changeDocumentId", os.Getenv("PIPER_changeDocumentId"), "ID of the change document to be checked for the status")
   164  	cmd.Flags().BoolVar(&stepConfig.FailIfStatusIsNotInDevelopment, "failIfStatusIsNotInDevelopment", true, "lets the build fail in case the change is not in status 'in developent'. Otherwise a warning is emitted to the log")
   165  	cmd.Flags().StringSliceVar(&stepConfig.CmClientOpts, "cmClientOpts", []string{}, "additional options passed to cm client, e.g. for troubleshooting")
   166  
   167  	cmd.MarkFlagRequired("endpoint")
   168  	cmd.MarkFlagRequired("username")
   169  	cmd.MarkFlagRequired("password")
   170  	cmd.MarkFlagRequired("changeDocumentId")
   171  }
   172  
   173  // retrieve step metadata
   174  func isChangeInDevelopmentMetadata() config.StepData {
   175  	var theMetaData = config.StepData{
   176  		Metadata: config.StepMetadata{
   177  			Name:        "isChangeInDevelopment",
   178  			Aliases:     []config.Alias{},
   179  			Description: "This step checks if a certain change is in status 'in development'",
   180  		},
   181  		Spec: config.StepSpec{
   182  			Inputs: config.StepInputs{
   183  				Secrets: []config.StepSecrets{
   184  					{Name: "credentialsId", Description: "Jenkins 'Username with password' credentials ID containing user and password to authenticate against the ABAP backend", Type: "jenkins", Aliases: []config.Alias{{Name: "changeManagement/credentialsId", Deprecated: false}}},
   185  				},
   186  				Parameters: []config.StepParameters{
   187  					{
   188  						Name:        "endpoint",
   189  						ResourceRef: []config.ResourceReference{},
   190  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS", "GENERAL"},
   191  						Type:        "string",
   192  						Mandatory:   true,
   193  						Aliases:     []config.Alias{{Name: "changeManagement/endpoint"}},
   194  						Default:     os.Getenv("PIPER_endpoint"),
   195  					},
   196  					{
   197  						Name: "username",
   198  						ResourceRef: []config.ResourceReference{
   199  							{
   200  								Name:  "credentialsId",
   201  								Param: "username",
   202  								Type:  "secret",
   203  							},
   204  						},
   205  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS", "GENERAL"},
   206  						Type:      "string",
   207  						Mandatory: true,
   208  						Aliases:   []config.Alias{},
   209  						Default:   os.Getenv("PIPER_username"),
   210  					},
   211  					{
   212  						Name: "password",
   213  						ResourceRef: []config.ResourceReference{
   214  							{
   215  								Name:  "credentialsId",
   216  								Param: "password",
   217  								Type:  "secret",
   218  							},
   219  						},
   220  						Scope:     []string{"PARAMETERS"},
   221  						Type:      "string",
   222  						Mandatory: true,
   223  						Aliases:   []config.Alias{},
   224  						Default:   os.Getenv("PIPER_password"),
   225  					},
   226  					{
   227  						Name: "changeDocumentId",
   228  						ResourceRef: []config.ResourceReference{
   229  							{
   230  								Name:  "commonPipelineEnvironment",
   231  								Param: "custom/changeDocumentId",
   232  							},
   233  						},
   234  						Scope:     []string{"PARAMETERS"},
   235  						Type:      "string",
   236  						Mandatory: true,
   237  						Aliases:   []config.Alias{},
   238  						Default:   os.Getenv("PIPER_changeDocumentId"),
   239  					},
   240  					{
   241  						Name:        "failIfStatusIsNotInDevelopment",
   242  						ResourceRef: []config.ResourceReference{},
   243  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   244  						Type:        "bool",
   245  						Mandatory:   false,
   246  						Aliases:     []config.Alias{},
   247  						Default:     true,
   248  					},
   249  					{
   250  						Name:        "cmClientOpts",
   251  						ResourceRef: []config.ResourceReference{},
   252  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   253  						Type:        "[]string",
   254  						Mandatory:   false,
   255  						Aliases:     []config.Alias{{Name: "clientOpts"}, {Name: "changeManagement/clientOpts"}},
   256  						Default:     []string{},
   257  					},
   258  				},
   259  			},
   260  			Containers: []config.Container{
   261  				{Name: "cmclient", Image: "ppiper/cm-client:3.0.0.0"},
   262  			},
   263  			Outputs: config.StepOutputs{
   264  				Resources: []config.StepResources{
   265  					{
   266  						Name: "commonPipelineEnvironment",
   267  						Type: "piperEnvironment",
   268  						Parameters: []map[string]interface{}{
   269  							{"name": "custom/isChangeInDevelopment", "type": "bool"},
   270  						},
   271  					},
   272  				},
   273  			},
   274  		},
   275  	}
   276  	return theMetaData
   277  }