github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/cmd/shellExecute_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  	"time"
     9  
    10  	"github.com/SAP/jenkins-library/pkg/config"
    11  	"github.com/SAP/jenkins-library/pkg/log"
    12  	"github.com/SAP/jenkins-library/pkg/splunk"
    13  	"github.com/SAP/jenkins-library/pkg/telemetry"
    14  	"github.com/SAP/jenkins-library/pkg/validation"
    15  	"github.com/spf13/cobra"
    16  )
    17  
    18  type shellExecuteOptions struct {
    19  	Sources         []string `json:"sources,omitempty"`
    20  	GithubToken     string   `json:"githubToken,omitempty"`
    21  	ScriptArguments []string `json:"scriptArguments,omitempty"`
    22  }
    23  
    24  // ShellExecuteCommand Step executes defined script
    25  func ShellExecuteCommand() *cobra.Command {
    26  	const STEP_NAME = "shellExecute"
    27  
    28  	metadata := shellExecuteMetadata()
    29  	var stepConfig shellExecuteOptions
    30  	var startTime time.Time
    31  	var logCollector *log.CollectorHook
    32  	var splunkClient *splunk.Splunk
    33  	telemetryClient := &telemetry.Telemetry{}
    34  
    35  	var createShellExecuteCmd = &cobra.Command{
    36  		Use:   STEP_NAME,
    37  		Short: "Step executes defined script",
    38  		Long:  `Step executes defined script provided in the 'sources' parameter`,
    39  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    40  			startTime = time.Now()
    41  			log.SetStepName(STEP_NAME)
    42  			log.SetVerbose(GeneralConfig.Verbose)
    43  
    44  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    45  
    46  			path, _ := os.Getwd()
    47  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    48  			log.RegisterHook(fatalHook)
    49  
    50  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    51  			if err != nil {
    52  				log.SetErrorCategory(log.ErrorConfiguration)
    53  				return err
    54  			}
    55  			log.RegisterSecret(stepConfig.GithubToken)
    56  
    57  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    58  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    59  				log.RegisterHook(&sentryHook)
    60  			}
    61  
    62  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    63  				splunkClient = &splunk.Splunk{}
    64  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    65  				log.RegisterHook(logCollector)
    66  			}
    67  
    68  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
    69  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
    70  			}
    71  
    72  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    73  			if err != nil {
    74  				return err
    75  			}
    76  			if err = validation.ValidateStruct(stepConfig); err != nil {
    77  				log.SetErrorCategory(log.ErrorConfiguration)
    78  				return err
    79  			}
    80  
    81  			return nil
    82  		},
    83  		Run: func(_ *cobra.Command, _ []string) {
    84  			stepTelemetryData := telemetry.CustomData{}
    85  			stepTelemetryData.ErrorCode = "1"
    86  			handler := func() {
    87  				config.RemoveVaultSecretFiles()
    88  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
    89  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
    90  				stepTelemetryData.PiperCommitHash = GitCommit
    91  				telemetryClient.SetData(&stepTelemetryData)
    92  				telemetryClient.Send()
    93  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    94  					splunkClient.Initialize(GeneralConfig.CorrelationID,
    95  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
    96  						GeneralConfig.HookConfig.SplunkConfig.Token,
    97  						GeneralConfig.HookConfig.SplunkConfig.Index,
    98  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
    99  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   100  				}
   101  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   102  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   103  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   104  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   105  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   106  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   107  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   108  				}
   109  			}
   110  			log.DeferExitHandler(handler)
   111  			defer handler()
   112  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   113  			shellExecute(stepConfig, &stepTelemetryData)
   114  			stepTelemetryData.ErrorCode = "0"
   115  			log.Entry().Info("SUCCESS")
   116  		},
   117  	}
   118  
   119  	addShellExecuteFlags(createShellExecuteCmd, &stepConfig)
   120  	return createShellExecuteCmd
   121  }
   122  
   123  func addShellExecuteFlags(cmd *cobra.Command, stepConfig *shellExecuteOptions) {
   124  	cmd.Flags().StringSliceVar(&stepConfig.Sources, "sources", []string{}, "Scripts paths that must be present in the current workspace or https links to scripts. Only https urls from github are allowed and must be in the format :https://{githubBaseurl}/api/v3/repos/{owner}/{repository}/contents/{path to script} Authentication for the download is only supported via the 'githubToken' param. Make sure the script has the necessary execute permissions.")
   125  	cmd.Flags().StringVar(&stepConfig.GithubToken, "githubToken", os.Getenv("PIPER_githubToken"), "GitHub personal access token as per https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line")
   126  	cmd.Flags().StringSliceVar(&stepConfig.ScriptArguments, "scriptArguments", []string{}, "scriptArguments that are needed to be passed to scripts. the scriptArguments list is a flat list and has a positional relationship to the `sources` param. For e.g. The scriptArguments string at position 1 will be considered as the argument(s) for script at position 1 in `sources` list. For multiple arguments for a script please add them as a comma seperated string.")
   127  
   128  }
   129  
   130  // retrieve step metadata
   131  func shellExecuteMetadata() config.StepData {
   132  	var theMetaData = config.StepData{
   133  		Metadata: config.StepMetadata{
   134  			Name:        "shellExecute",
   135  			Aliases:     []config.Alias{},
   136  			Description: "Step executes defined script",
   137  		},
   138  		Spec: config.StepSpec{
   139  			Inputs: config.StepInputs{
   140  				Secrets: []config.StepSecrets{
   141  					{Name: "githubTokenCredentialsId", Description: "Jenkins credentials ID containing the github token.", Type: "jenkins"},
   142  				},
   143  				Parameters: []config.StepParameters{
   144  					{
   145  						Name:        "sources",
   146  						ResourceRef: []config.ResourceReference{},
   147  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   148  						Type:        "[]string",
   149  						Mandatory:   false,
   150  						Aliases:     []config.Alias{},
   151  						Default:     []string{},
   152  					},
   153  					{
   154  						Name: "githubToken",
   155  						ResourceRef: []config.ResourceReference{
   156  							{
   157  								Name: "githubTokenCredentialsId",
   158  								Type: "secret",
   159  							},
   160  
   161  							{
   162  								Name:    "githubVaultSecretName",
   163  								Type:    "vaultSecret",
   164  								Default: "github",
   165  							},
   166  						},
   167  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   168  						Type:      "string",
   169  						Mandatory: false,
   170  						Aliases:   []config.Alias{{Name: "access_token"}},
   171  						Default:   os.Getenv("PIPER_githubToken"),
   172  					},
   173  					{
   174  						Name:        "scriptArguments",
   175  						ResourceRef: []config.ResourceReference{},
   176  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   177  						Type:        "[]string",
   178  						Mandatory:   false,
   179  						Aliases:     []config.Alias{},
   180  						Default:     []string{},
   181  					},
   182  				},
   183  			},
   184  			Containers: []config.Container{
   185  				{Name: "shell", Image: "node:lts-buster", WorkingDir: "/home/node"},
   186  			},
   187  		},
   188  	}
   189  	return theMetaData
   190  }