github.com/xgoffin/jenkins-library@v1.154.0/cmd/githubSetCommitStatus_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 githubSetCommitStatusOptions struct {
    19  	APIURL      string `json:"apiUrl,omitempty"`
    20  	CommitID    string `json:"commitId,omitempty"`
    21  	Context     string `json:"context,omitempty"`
    22  	Description string `json:"description,omitempty"`
    23  	Owner       string `json:"owner,omitempty"`
    24  	Repository  string `json:"repository,omitempty"`
    25  	Status      string `json:"status,omitempty" validate:"possible-values=failure pending success"`
    26  	TargetURL   string `json:"targetUrl,omitempty"`
    27  	Token       string `json:"token,omitempty"`
    28  }
    29  
    30  // GithubSetCommitStatusCommand Set a status of a certain commit.
    31  func GithubSetCommitStatusCommand() *cobra.Command {
    32  	const STEP_NAME = "githubSetCommitStatus"
    33  
    34  	metadata := githubSetCommitStatusMetadata()
    35  	var stepConfig githubSetCommitStatusOptions
    36  	var startTime time.Time
    37  	var logCollector *log.CollectorHook
    38  	var splunkClient *splunk.Splunk
    39  	telemetryClient := &telemetry.Telemetry{}
    40  
    41  	var createGithubSetCommitStatusCmd = &cobra.Command{
    42  		Use:   STEP_NAME,
    43  		Short: "Set a status of a certain commit.",
    44  		Long: `This step allows you to set a status for a certain commit.
    45  Details can be found here: https://developer.github.com/v3/repos/statuses/.
    46  
    47  Typically, following information is set:
    48  
    49  * state (pending, failure, success)
    50  * context
    51  * target URL (link to details)
    52  
    53  It can for example be used to create additional check indicators for a pull request which can be evaluated and also be enforced by GitHub configuration.`,
    54  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    55  			startTime = time.Now()
    56  			log.SetStepName(STEP_NAME)
    57  			log.SetVerbose(GeneralConfig.Verbose)
    58  
    59  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    60  
    61  			path, _ := os.Getwd()
    62  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    63  			log.RegisterHook(fatalHook)
    64  
    65  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    66  			if err != nil {
    67  				log.SetErrorCategory(log.ErrorConfiguration)
    68  				return err
    69  			}
    70  			log.RegisterSecret(stepConfig.Token)
    71  
    72  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    73  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    74  				log.RegisterHook(&sentryHook)
    75  			}
    76  
    77  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    78  				splunkClient = &splunk.Splunk{}
    79  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    80  				log.RegisterHook(logCollector)
    81  			}
    82  
    83  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    84  			if err != nil {
    85  				return err
    86  			}
    87  			if err = validation.ValidateStruct(stepConfig); err != nil {
    88  				log.SetErrorCategory(log.ErrorConfiguration)
    89  				return err
    90  			}
    91  
    92  			return nil
    93  		},
    94  		Run: func(_ *cobra.Command, _ []string) {
    95  			stepTelemetryData := telemetry.CustomData{}
    96  			stepTelemetryData.ErrorCode = "1"
    97  			handler := func() {
    98  				config.RemoveVaultSecretFiles()
    99  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   100  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   101  				stepTelemetryData.PiperCommitHash = GitCommit
   102  				telemetryClient.SetData(&stepTelemetryData)
   103  				telemetryClient.Send()
   104  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   105  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   106  				}
   107  			}
   108  			log.DeferExitHandler(handler)
   109  			defer handler()
   110  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   111  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   112  				splunkClient.Initialize(GeneralConfig.CorrelationID,
   113  					GeneralConfig.HookConfig.SplunkConfig.Dsn,
   114  					GeneralConfig.HookConfig.SplunkConfig.Token,
   115  					GeneralConfig.HookConfig.SplunkConfig.Index,
   116  					GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   117  			}
   118  			githubSetCommitStatus(stepConfig, &stepTelemetryData)
   119  			stepTelemetryData.ErrorCode = "0"
   120  			log.Entry().Info("SUCCESS")
   121  		},
   122  	}
   123  
   124  	addGithubSetCommitStatusFlags(createGithubSetCommitStatusCmd, &stepConfig)
   125  	return createGithubSetCommitStatusCmd
   126  }
   127  
   128  func addGithubSetCommitStatusFlags(cmd *cobra.Command, stepConfig *githubSetCommitStatusOptions) {
   129  	cmd.Flags().StringVar(&stepConfig.APIURL, "apiUrl", `https://api.github.com`, "Set the GitHub API URL.")
   130  	cmd.Flags().StringVar(&stepConfig.CommitID, "commitId", os.Getenv("PIPER_commitId"), "The commitId for which the status should be set.")
   131  	cmd.Flags().StringVar(&stepConfig.Context, "context", os.Getenv("PIPER_context"), "Label for the status which will for example show up in a pull request.")
   132  	cmd.Flags().StringVar(&stepConfig.Description, "description", os.Getenv("PIPER_description"), "Short description of the status.")
   133  	cmd.Flags().StringVar(&stepConfig.Owner, "owner", os.Getenv("PIPER_owner"), "Name of the GitHub organization.")
   134  	cmd.Flags().StringVar(&stepConfig.Repository, "repository", os.Getenv("PIPER_repository"), "Name of the GitHub repository.")
   135  	cmd.Flags().StringVar(&stepConfig.Status, "status", os.Getenv("PIPER_status"), "Status which should be set on the commitId.")
   136  	cmd.Flags().StringVar(&stepConfig.TargetURL, "targetUrl", os.Getenv("PIPER_targetUrl"), "Target URL to associate the status with.")
   137  	cmd.Flags().StringVar(&stepConfig.Token, "token", os.Getenv("PIPER_token"), "GitHub personal access token as per https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line.")
   138  
   139  	cmd.MarkFlagRequired("apiUrl")
   140  	cmd.MarkFlagRequired("commitId")
   141  	cmd.MarkFlagRequired("context")
   142  	cmd.MarkFlagRequired("owner")
   143  	cmd.MarkFlagRequired("repository")
   144  	cmd.MarkFlagRequired("status")
   145  	cmd.MarkFlagRequired("token")
   146  }
   147  
   148  // retrieve step metadata
   149  func githubSetCommitStatusMetadata() config.StepData {
   150  	var theMetaData = config.StepData{
   151  		Metadata: config.StepMetadata{
   152  			Name:        "githubSetCommitStatus",
   153  			Aliases:     []config.Alias{},
   154  			Description: "Set a status of a certain commit.",
   155  		},
   156  		Spec: config.StepSpec{
   157  			Inputs: config.StepInputs{
   158  				Secrets: []config.StepSecrets{
   159  					{Name: "githubTokenCredentialsId", Description: "Jenkins 'Secret text' credentials ID containing token to authenticate to GitHub.", Type: "jenkins"},
   160  				},
   161  				Parameters: []config.StepParameters{
   162  					{
   163  						Name:        "apiUrl",
   164  						ResourceRef: []config.ResourceReference{},
   165  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   166  						Type:        "string",
   167  						Mandatory:   true,
   168  						Aliases:     []config.Alias{{Name: "githubApiUrl"}},
   169  						Default:     `https://api.github.com`,
   170  					},
   171  					{
   172  						Name: "commitId",
   173  						ResourceRef: []config.ResourceReference{
   174  							{
   175  								Name:  "commonPipelineEnvironment",
   176  								Param: "git/commitId",
   177  							},
   178  						},
   179  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   180  						Type:      "string",
   181  						Mandatory: true,
   182  						Aliases:   []config.Alias{},
   183  						Default:   os.Getenv("PIPER_commitId"),
   184  					},
   185  					{
   186  						Name:        "context",
   187  						ResourceRef: []config.ResourceReference{},
   188  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   189  						Type:        "string",
   190  						Mandatory:   true,
   191  						Aliases:     []config.Alias{},
   192  						Default:     os.Getenv("PIPER_context"),
   193  					},
   194  					{
   195  						Name:        "description",
   196  						ResourceRef: []config.ResourceReference{},
   197  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   198  						Type:        "string",
   199  						Mandatory:   false,
   200  						Aliases:     []config.Alias{},
   201  						Default:     os.Getenv("PIPER_description"),
   202  					},
   203  					{
   204  						Name: "owner",
   205  						ResourceRef: []config.ResourceReference{
   206  							{
   207  								Name:  "commonPipelineEnvironment",
   208  								Param: "github/owner",
   209  							},
   210  						},
   211  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   212  						Type:      "string",
   213  						Mandatory: true,
   214  						Aliases:   []config.Alias{{Name: "githubOrg"}},
   215  						Default:   os.Getenv("PIPER_owner"),
   216  					},
   217  					{
   218  						Name: "repository",
   219  						ResourceRef: []config.ResourceReference{
   220  							{
   221  								Name:  "commonPipelineEnvironment",
   222  								Param: "github/repository",
   223  							},
   224  						},
   225  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   226  						Type:      "string",
   227  						Mandatory: true,
   228  						Aliases:   []config.Alias{{Name: "githubRepo"}},
   229  						Default:   os.Getenv("PIPER_repository"),
   230  					},
   231  					{
   232  						Name:        "status",
   233  						ResourceRef: []config.ResourceReference{},
   234  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   235  						Type:        "string",
   236  						Mandatory:   true,
   237  						Aliases:     []config.Alias{},
   238  						Default:     os.Getenv("PIPER_status"),
   239  					},
   240  					{
   241  						Name:        "targetUrl",
   242  						ResourceRef: []config.ResourceReference{},
   243  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   244  						Type:        "string",
   245  						Mandatory:   false,
   246  						Aliases:     []config.Alias{},
   247  						Default:     os.Getenv("PIPER_targetUrl"),
   248  					},
   249  					{
   250  						Name: "token",
   251  						ResourceRef: []config.ResourceReference{
   252  							{
   253  								Name: "githubTokenCredentialsId",
   254  								Type: "secret",
   255  							},
   256  
   257  							{
   258  								Name:    "githubVaultSecretName",
   259  								Type:    "vaultSecret",
   260  								Default: "github",
   261  							},
   262  						},
   263  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   264  						Type:      "string",
   265  						Mandatory: true,
   266  						Aliases:   []config.Alias{{Name: "githubToken"}, {Name: "access_token"}},
   267  						Default:   os.Getenv("PIPER_token"),
   268  					},
   269  				},
   270  			},
   271  		},
   272  	}
   273  	return theMetaData
   274  }