github.com/xgoffin/jenkins-library@v1.154.0/cmd/githubCommentIssue_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 githubCommentIssueOptions struct {
    19  	APIURL     string `json:"apiUrl,omitempty"`
    20  	Body       string `json:"body,omitempty"`
    21  	Number     int    `json:"number,omitempty"`
    22  	Owner      string `json:"owner,omitempty"`
    23  	Repository string `json:"repository,omitempty"`
    24  	Token      string `json:"token,omitempty"`
    25  }
    26  
    27  // GithubCommentIssueCommand Comment on GitHub issues and pull requests.
    28  func GithubCommentIssueCommand() *cobra.Command {
    29  	const STEP_NAME = "githubCommentIssue"
    30  
    31  	metadata := githubCommentIssueMetadata()
    32  	var stepConfig githubCommentIssueOptions
    33  	var startTime time.Time
    34  	var logCollector *log.CollectorHook
    35  	var splunkClient *splunk.Splunk
    36  	telemetryClient := &telemetry.Telemetry{}
    37  
    38  	var createGithubCommentIssueCmd = &cobra.Command{
    39  		Use:   STEP_NAME,
    40  		Short: "Comment on GitHub issues and pull requests.",
    41  		Long: `This step allows you to add comments to existing GitHub issues or pull requests.
    42  
    43  Pull requests are considered similar to issues and thus adding a comment can be done to an existing pull request as well.
    44  This comes in very handy when you want to make developers aware of certain things during a PR voting process, for example.`,
    45  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    46  			startTime = time.Now()
    47  			log.SetStepName(STEP_NAME)
    48  			log.SetVerbose(GeneralConfig.Verbose)
    49  
    50  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    51  
    52  			path, _ := os.Getwd()
    53  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    54  			log.RegisterHook(fatalHook)
    55  
    56  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    57  			if err != nil {
    58  				log.SetErrorCategory(log.ErrorConfiguration)
    59  				return err
    60  			}
    61  			log.RegisterSecret(stepConfig.Token)
    62  
    63  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    64  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    65  				log.RegisterHook(&sentryHook)
    66  			}
    67  
    68  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    69  				splunkClient = &splunk.Splunk{}
    70  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    71  				log.RegisterHook(logCollector)
    72  			}
    73  
    74  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    75  			if err != nil {
    76  				return err
    77  			}
    78  			if err = validation.ValidateStruct(stepConfig); err != nil {
    79  				log.SetErrorCategory(log.ErrorConfiguration)
    80  				return err
    81  			}
    82  
    83  			return nil
    84  		},
    85  		Run: func(_ *cobra.Command, _ []string) {
    86  			stepTelemetryData := telemetry.CustomData{}
    87  			stepTelemetryData.ErrorCode = "1"
    88  			handler := func() {
    89  				config.RemoveVaultSecretFiles()
    90  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
    91  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
    92  				stepTelemetryData.PiperCommitHash = GitCommit
    93  				telemetryClient.SetData(&stepTelemetryData)
    94  				telemetryClient.Send()
    95  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    96  					splunkClient.Send(telemetryClient.GetData(), logCollector)
    97  				}
    98  			}
    99  			log.DeferExitHandler(handler)
   100  			defer handler()
   101  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   102  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   103  				splunkClient.Initialize(GeneralConfig.CorrelationID,
   104  					GeneralConfig.HookConfig.SplunkConfig.Dsn,
   105  					GeneralConfig.HookConfig.SplunkConfig.Token,
   106  					GeneralConfig.HookConfig.SplunkConfig.Index,
   107  					GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   108  			}
   109  			githubCommentIssue(stepConfig, &stepTelemetryData)
   110  			stepTelemetryData.ErrorCode = "0"
   111  			log.Entry().Info("SUCCESS")
   112  		},
   113  	}
   114  
   115  	addGithubCommentIssueFlags(createGithubCommentIssueCmd, &stepConfig)
   116  	return createGithubCommentIssueCmd
   117  }
   118  
   119  func addGithubCommentIssueFlags(cmd *cobra.Command, stepConfig *githubCommentIssueOptions) {
   120  	cmd.Flags().StringVar(&stepConfig.APIURL, "apiUrl", `https://api.github.com`, "Set the GitHub API url.")
   121  	cmd.Flags().StringVar(&stepConfig.Body, "body", os.Getenv("PIPER_body"), "Defines the content of the comment, e.g. using markdown syntax.")
   122  	cmd.Flags().IntVar(&stepConfig.Number, "number", 0, "Defines the number of the GitHub issue/pull request.")
   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().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.")
   126  
   127  	cmd.MarkFlagRequired("apiUrl")
   128  	cmd.MarkFlagRequired("body")
   129  	cmd.MarkFlagRequired("number")
   130  	cmd.MarkFlagRequired("owner")
   131  	cmd.MarkFlagRequired("repository")
   132  	cmd.MarkFlagRequired("token")
   133  }
   134  
   135  // retrieve step metadata
   136  func githubCommentIssueMetadata() config.StepData {
   137  	var theMetaData = config.StepData{
   138  		Metadata: config.StepMetadata{
   139  			Name:        "githubCommentIssue",
   140  			Aliases:     []config.Alias{},
   141  			Description: "Comment on GitHub issues and pull requests.",
   142  		},
   143  		Spec: config.StepSpec{
   144  			Inputs: config.StepInputs{
   145  				Secrets: []config.StepSecrets{
   146  					{Name: "githubTokenCredentialsId", Description: "Jenkins 'Secret text' credentials ID containing token to authenticate to GitHub.", Type: "jenkins"},
   147  				},
   148  				Parameters: []config.StepParameters{
   149  					{
   150  						Name:        "apiUrl",
   151  						ResourceRef: []config.ResourceReference{},
   152  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   153  						Type:        "string",
   154  						Mandatory:   true,
   155  						Aliases:     []config.Alias{{Name: "githubApiUrl"}},
   156  						Default:     `https://api.github.com`,
   157  					},
   158  					{
   159  						Name:        "body",
   160  						ResourceRef: []config.ResourceReference{},
   161  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   162  						Type:        "string",
   163  						Mandatory:   true,
   164  						Aliases:     []config.Alias{},
   165  						Default:     os.Getenv("PIPER_body"),
   166  					},
   167  					{
   168  						Name:        "number",
   169  						ResourceRef: []config.ResourceReference{},
   170  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   171  						Type:        "int",
   172  						Mandatory:   true,
   173  						Aliases:     []config.Alias{},
   174  						Default:     0,
   175  					},
   176  					{
   177  						Name: "owner",
   178  						ResourceRef: []config.ResourceReference{
   179  							{
   180  								Name:  "commonPipelineEnvironment",
   181  								Param: "github/owner",
   182  							},
   183  						},
   184  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   185  						Type:      "string",
   186  						Mandatory: true,
   187  						Aliases:   []config.Alias{{Name: "githubOrg"}},
   188  						Default:   os.Getenv("PIPER_owner"),
   189  					},
   190  					{
   191  						Name: "repository",
   192  						ResourceRef: []config.ResourceReference{
   193  							{
   194  								Name:  "commonPipelineEnvironment",
   195  								Param: "github/repository",
   196  							},
   197  						},
   198  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   199  						Type:      "string",
   200  						Mandatory: true,
   201  						Aliases:   []config.Alias{{Name: "githubRepo"}},
   202  						Default:   os.Getenv("PIPER_repository"),
   203  					},
   204  					{
   205  						Name: "token",
   206  						ResourceRef: []config.ResourceReference{
   207  							{
   208  								Name: "githubTokenCredentialsId",
   209  								Type: "secret",
   210  							},
   211  
   212  							{
   213  								Name:    "githubVaultSecretName",
   214  								Type:    "vaultSecret",
   215  								Default: "github",
   216  							},
   217  						},
   218  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   219  						Type:      "string",
   220  						Mandatory: true,
   221  						Aliases:   []config.Alias{{Name: "githubToken"}, {Name: "access_token"}},
   222  						Default:   os.Getenv("PIPER_token"),
   223  					},
   224  				},
   225  			},
   226  		},
   227  	}
   228  	return theMetaData
   229  }