github.com/xgoffin/jenkins-library@v1.154.0/cmd/githubCheckBranchProtection_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 githubCheckBranchProtectionOptions struct {
    19  	APIURL                       string   `json:"apiUrl,omitempty"`
    20  	Branch                       string   `json:"branch,omitempty"`
    21  	Owner                        string   `json:"owner,omitempty"`
    22  	Repository                   string   `json:"repository,omitempty"`
    23  	RequiredChecks               []string `json:"requiredChecks,omitempty"`
    24  	RequireEnforceAdmins         bool     `json:"requireEnforceAdmins,omitempty"`
    25  	RequiredApprovingReviewCount int      `json:"requiredApprovingReviewCount,omitempty"`
    26  	Token                        string   `json:"token,omitempty"`
    27  }
    28  
    29  // GithubCheckBranchProtectionCommand Check branch protection of a GitHub branch
    30  func GithubCheckBranchProtectionCommand() *cobra.Command {
    31  	const STEP_NAME = "githubCheckBranchProtection"
    32  
    33  	metadata := githubCheckBranchProtectionMetadata()
    34  	var stepConfig githubCheckBranchProtectionOptions
    35  	var startTime time.Time
    36  	var logCollector *log.CollectorHook
    37  	var splunkClient *splunk.Splunk
    38  	telemetryClient := &telemetry.Telemetry{}
    39  
    40  	var createGithubCheckBranchProtectionCmd = &cobra.Command{
    41  		Use:   STEP_NAME,
    42  		Short: "Check branch protection of a GitHub branch",
    43  		Long: `This step allows you to check if certain branch protection rules are fulfilled.
    44  
    45  It can for example be used to verify if certain status checks are mandatory. This can be helpful to decide if a certain check needs to be performed again after merging a pull request.`,
    46  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    47  			startTime = time.Now()
    48  			log.SetStepName(STEP_NAME)
    49  			log.SetVerbose(GeneralConfig.Verbose)
    50  
    51  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    52  
    53  			path, _ := os.Getwd()
    54  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    55  			log.RegisterHook(fatalHook)
    56  
    57  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    58  			if err != nil {
    59  				log.SetErrorCategory(log.ErrorConfiguration)
    60  				return err
    61  			}
    62  			log.RegisterSecret(stepConfig.Token)
    63  
    64  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    65  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    66  				log.RegisterHook(&sentryHook)
    67  			}
    68  
    69  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    70  				splunkClient = &splunk.Splunk{}
    71  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    72  				log.RegisterHook(logCollector)
    73  			}
    74  
    75  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    76  			if err != nil {
    77  				return err
    78  			}
    79  			if err = validation.ValidateStruct(stepConfig); err != nil {
    80  				log.SetErrorCategory(log.ErrorConfiguration)
    81  				return err
    82  			}
    83  
    84  			return nil
    85  		},
    86  		Run: func(_ *cobra.Command, _ []string) {
    87  			stepTelemetryData := telemetry.CustomData{}
    88  			stepTelemetryData.ErrorCode = "1"
    89  			handler := func() {
    90  				config.RemoveVaultSecretFiles()
    91  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
    92  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
    93  				stepTelemetryData.PiperCommitHash = GitCommit
    94  				telemetryClient.SetData(&stepTelemetryData)
    95  				telemetryClient.Send()
    96  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    97  					splunkClient.Send(telemetryClient.GetData(), logCollector)
    98  				}
    99  			}
   100  			log.DeferExitHandler(handler)
   101  			defer handler()
   102  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   103  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   104  				splunkClient.Initialize(GeneralConfig.CorrelationID,
   105  					GeneralConfig.HookConfig.SplunkConfig.Dsn,
   106  					GeneralConfig.HookConfig.SplunkConfig.Token,
   107  					GeneralConfig.HookConfig.SplunkConfig.Index,
   108  					GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   109  			}
   110  			githubCheckBranchProtection(stepConfig, &stepTelemetryData)
   111  			stepTelemetryData.ErrorCode = "0"
   112  			log.Entry().Info("SUCCESS")
   113  		},
   114  	}
   115  
   116  	addGithubCheckBranchProtectionFlags(createGithubCheckBranchProtectionCmd, &stepConfig)
   117  	return createGithubCheckBranchProtectionCmd
   118  }
   119  
   120  func addGithubCheckBranchProtectionFlags(cmd *cobra.Command, stepConfig *githubCheckBranchProtectionOptions) {
   121  	cmd.Flags().StringVar(&stepConfig.APIURL, "apiUrl", `https://api.github.com`, "Set the GitHub API url.")
   122  	cmd.Flags().StringVar(&stepConfig.Branch, "branch", `master`, "The name of the branch for which the protection settings should be checked.")
   123  	cmd.Flags().StringVar(&stepConfig.Owner, "owner", os.Getenv("PIPER_owner"), "Name of the GitHub organization.")
   124  	cmd.Flags().StringVar(&stepConfig.Repository, "repository", os.Getenv("PIPER_repository"), "Name of the GitHub repository.")
   125  	cmd.Flags().StringSliceVar(&stepConfig.RequiredChecks, "requiredChecks", []string{}, "List of checks which have to be set to 'required' in the GitHub repository configuration.")
   126  	cmd.Flags().BoolVar(&stepConfig.RequireEnforceAdmins, "requireEnforceAdmins", false, "Check if 'Include Administrators' option is set in the GitHub repository configuration.")
   127  	cmd.Flags().IntVar(&stepConfig.RequiredApprovingReviewCount, "requiredApprovingReviewCount", 0, "Check if 'Require pull request reviews before merging' option is set with at least the defined number of reviewers in the GitHub repository configuration.")
   128  	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.")
   129  
   130  	cmd.MarkFlagRequired("apiUrl")
   131  	cmd.MarkFlagRequired("branch")
   132  	cmd.MarkFlagRequired("owner")
   133  	cmd.MarkFlagRequired("repository")
   134  	cmd.MarkFlagRequired("token")
   135  }
   136  
   137  // retrieve step metadata
   138  func githubCheckBranchProtectionMetadata() config.StepData {
   139  	var theMetaData = config.StepData{
   140  		Metadata: config.StepMetadata{
   141  			Name:        "githubCheckBranchProtection",
   142  			Aliases:     []config.Alias{},
   143  			Description: "Check branch protection of a GitHub branch",
   144  		},
   145  		Spec: config.StepSpec{
   146  			Inputs: config.StepInputs{
   147  				Secrets: []config.StepSecrets{
   148  					{Name: "githubTokenCredentialsId", Description: "Jenkins 'Secret text' credentials ID containing token to authenticate to GitHub.", Type: "jenkins"},
   149  				},
   150  				Parameters: []config.StepParameters{
   151  					{
   152  						Name:        "apiUrl",
   153  						ResourceRef: []config.ResourceReference{},
   154  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   155  						Type:        "string",
   156  						Mandatory:   true,
   157  						Aliases:     []config.Alias{{Name: "githubApiUrl"}},
   158  						Default:     `https://api.github.com`,
   159  					},
   160  					{
   161  						Name:        "branch",
   162  						ResourceRef: []config.ResourceReference{},
   163  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   164  						Type:        "string",
   165  						Mandatory:   true,
   166  						Aliases:     []config.Alias{},
   167  						Default:     `master`,
   168  					},
   169  					{
   170  						Name: "owner",
   171  						ResourceRef: []config.ResourceReference{
   172  							{
   173  								Name:  "commonPipelineEnvironment",
   174  								Param: "github/owner",
   175  							},
   176  						},
   177  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   178  						Type:      "string",
   179  						Mandatory: true,
   180  						Aliases:   []config.Alias{{Name: "githubOrg"}},
   181  						Default:   os.Getenv("PIPER_owner"),
   182  					},
   183  					{
   184  						Name: "repository",
   185  						ResourceRef: []config.ResourceReference{
   186  							{
   187  								Name:  "commonPipelineEnvironment",
   188  								Param: "github/repository",
   189  							},
   190  						},
   191  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   192  						Type:      "string",
   193  						Mandatory: true,
   194  						Aliases:   []config.Alias{{Name: "githubRepo"}},
   195  						Default:   os.Getenv("PIPER_repository"),
   196  					},
   197  					{
   198  						Name:        "requiredChecks",
   199  						ResourceRef: []config.ResourceReference{},
   200  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   201  						Type:        "[]string",
   202  						Mandatory:   false,
   203  						Aliases:     []config.Alias{},
   204  						Default:     []string{},
   205  					},
   206  					{
   207  						Name:        "requireEnforceAdmins",
   208  						ResourceRef: []config.ResourceReference{},
   209  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   210  						Type:        "bool",
   211  						Mandatory:   false,
   212  						Aliases:     []config.Alias{},
   213  						Default:     false,
   214  					},
   215  					{
   216  						Name:        "requiredApprovingReviewCount",
   217  						ResourceRef: []config.ResourceReference{},
   218  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   219  						Type:        "int",
   220  						Mandatory:   false,
   221  						Aliases:     []config.Alias{},
   222  						Default:     0,
   223  					},
   224  					{
   225  						Name: "token",
   226  						ResourceRef: []config.ResourceReference{
   227  							{
   228  								Name: "githubTokenCredentialsId",
   229  								Type: "secret",
   230  							},
   231  
   232  							{
   233  								Name:    "githubVaultSecretName",
   234  								Type:    "vaultSecret",
   235  								Default: "github",
   236  							},
   237  						},
   238  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   239  						Type:      "string",
   240  						Mandatory: true,
   241  						Aliases:   []config.Alias{{Name: "githubToken"}, {Name: "access_token"}},
   242  						Default:   os.Getenv("PIPER_token"),
   243  					},
   244  				},
   245  			},
   246  		},
   247  	}
   248  	return theMetaData
   249  }