github.com/SAP/jenkins-library@v1.362.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 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 { 70 splunkClient = &splunk.Splunk{} 71 logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID} 72 log.RegisterHook(logCollector) 73 } 74 75 if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil { 76 log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook") 77 } 78 79 validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages()) 80 if err != nil { 81 return err 82 } 83 if err = validation.ValidateStruct(stepConfig); err != nil { 84 log.SetErrorCategory(log.ErrorConfiguration) 85 return err 86 } 87 88 return nil 89 }, 90 Run: func(_ *cobra.Command, _ []string) { 91 stepTelemetryData := telemetry.CustomData{} 92 stepTelemetryData.ErrorCode = "1" 93 handler := func() { 94 config.RemoveVaultSecretFiles() 95 stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds()) 96 stepTelemetryData.ErrorCategory = log.GetErrorCategory().String() 97 stepTelemetryData.PiperCommitHash = GitCommit 98 telemetryClient.SetData(&stepTelemetryData) 99 telemetryClient.Send() 100 if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { 101 splunkClient.Initialize(GeneralConfig.CorrelationID, 102 GeneralConfig.HookConfig.SplunkConfig.Dsn, 103 GeneralConfig.HookConfig.SplunkConfig.Token, 104 GeneralConfig.HookConfig.SplunkConfig.Index, 105 GeneralConfig.HookConfig.SplunkConfig.SendLogs) 106 splunkClient.Send(telemetryClient.GetData(), logCollector) 107 } 108 if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 { 109 splunkClient.Initialize(GeneralConfig.CorrelationID, 110 GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint, 111 GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken, 112 GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex, 113 GeneralConfig.HookConfig.SplunkConfig.SendLogs) 114 splunkClient.Send(telemetryClient.GetData(), logCollector) 115 } 116 } 117 log.DeferExitHandler(handler) 118 defer handler() 119 telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token) 120 githubCheckBranchProtection(stepConfig, &stepTelemetryData) 121 stepTelemetryData.ErrorCode = "0" 122 log.Entry().Info("SUCCESS") 123 }, 124 } 125 126 addGithubCheckBranchProtectionFlags(createGithubCheckBranchProtectionCmd, &stepConfig) 127 return createGithubCheckBranchProtectionCmd 128 } 129 130 func addGithubCheckBranchProtectionFlags(cmd *cobra.Command, stepConfig *githubCheckBranchProtectionOptions) { 131 cmd.Flags().StringVar(&stepConfig.APIURL, "apiUrl", `https://api.github.com`, "Set the GitHub API url.") 132 cmd.Flags().StringVar(&stepConfig.Branch, "branch", `master`, "The name of the branch for which the protection settings should be checked.") 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().StringSliceVar(&stepConfig.RequiredChecks, "requiredChecks", []string{}, "List of checks which have to be set to 'required' in the GitHub repository configuration.") 136 cmd.Flags().BoolVar(&stepConfig.RequireEnforceAdmins, "requireEnforceAdmins", false, "Check if 'Include Administrators' option is set in the GitHub repository configuration.") 137 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.") 138 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.") 139 140 cmd.MarkFlagRequired("apiUrl") 141 cmd.MarkFlagRequired("branch") 142 cmd.MarkFlagRequired("owner") 143 cmd.MarkFlagRequired("repository") 144 cmd.MarkFlagRequired("token") 145 } 146 147 // retrieve step metadata 148 func githubCheckBranchProtectionMetadata() config.StepData { 149 var theMetaData = config.StepData{ 150 Metadata: config.StepMetadata{ 151 Name: "githubCheckBranchProtection", 152 Aliases: []config.Alias{}, 153 Description: "Check branch protection of a GitHub branch", 154 }, 155 Spec: config.StepSpec{ 156 Inputs: config.StepInputs{ 157 Secrets: []config.StepSecrets{ 158 {Name: "githubTokenCredentialsId", Description: "Jenkins 'Secret text' credentials ID containing token to authenticate to GitHub.", Type: "jenkins"}, 159 }, 160 Parameters: []config.StepParameters{ 161 { 162 Name: "apiUrl", 163 ResourceRef: []config.ResourceReference{}, 164 Scope: []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"}, 165 Type: "string", 166 Mandatory: true, 167 Aliases: []config.Alias{{Name: "githubApiUrl"}}, 168 Default: `https://api.github.com`, 169 }, 170 { 171 Name: "branch", 172 ResourceRef: []config.ResourceReference{}, 173 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 174 Type: "string", 175 Mandatory: true, 176 Aliases: []config.Alias{}, 177 Default: `master`, 178 }, 179 { 180 Name: "owner", 181 ResourceRef: []config.ResourceReference{ 182 { 183 Name: "commonPipelineEnvironment", 184 Param: "github/owner", 185 }, 186 }, 187 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 188 Type: "string", 189 Mandatory: true, 190 Aliases: []config.Alias{{Name: "githubOrg"}}, 191 Default: os.Getenv("PIPER_owner"), 192 }, 193 { 194 Name: "repository", 195 ResourceRef: []config.ResourceReference{ 196 { 197 Name: "commonPipelineEnvironment", 198 Param: "github/repository", 199 }, 200 }, 201 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 202 Type: "string", 203 Mandatory: true, 204 Aliases: []config.Alias{{Name: "githubRepo"}}, 205 Default: os.Getenv("PIPER_repository"), 206 }, 207 { 208 Name: "requiredChecks", 209 ResourceRef: []config.ResourceReference{}, 210 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 211 Type: "[]string", 212 Mandatory: false, 213 Aliases: []config.Alias{}, 214 Default: []string{}, 215 }, 216 { 217 Name: "requireEnforceAdmins", 218 ResourceRef: []config.ResourceReference{}, 219 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 220 Type: "bool", 221 Mandatory: false, 222 Aliases: []config.Alias{}, 223 Default: false, 224 }, 225 { 226 Name: "requiredApprovingReviewCount", 227 ResourceRef: []config.ResourceReference{}, 228 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 229 Type: "int", 230 Mandatory: false, 231 Aliases: []config.Alias{}, 232 Default: 0, 233 }, 234 { 235 Name: "token", 236 ResourceRef: []config.ResourceReference{ 237 { 238 Name: "githubTokenCredentialsId", 239 Type: "secret", 240 }, 241 242 { 243 Name: "githubVaultSecretName", 244 Type: "vaultSecret", 245 Default: "github", 246 }, 247 }, 248 Scope: []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"}, 249 Type: "string", 250 Mandatory: true, 251 Aliases: []config.Alias{{Name: "githubToken"}, {Name: "access_token"}}, 252 Default: os.Getenv("PIPER_token"), 253 }, 254 }, 255 }, 256 }, 257 } 258 return theMetaData 259 }