github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/cmd/githubPublishRelease_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 githubPublishReleaseOptions struct {
    19  	AddClosedIssues       bool     `json:"addClosedIssues,omitempty"`
    20  	AddDeltaToLastRelease bool     `json:"addDeltaToLastRelease,omitempty"`
    21  	APIURL                string   `json:"apiUrl,omitempty"`
    22  	AssetPath             string   `json:"assetPath,omitempty"`
    23  	AssetPathList         []string `json:"assetPathList,omitempty"`
    24  	Commitish             string   `json:"commitish,omitempty"`
    25  	ExcludeLabels         []string `json:"excludeLabels,omitempty"`
    26  	Labels                []string `json:"labels,omitempty"`
    27  	Owner                 string   `json:"owner,omitempty"`
    28  	PreRelease            bool     `json:"preRelease,omitempty"`
    29  	ReleaseBodyHeader     string   `json:"releaseBodyHeader,omitempty"`
    30  	Repository            string   `json:"repository,omitempty"`
    31  	ServerURL             string   `json:"serverUrl,omitempty"`
    32  	TagPrefix             string   `json:"tagPrefix,omitempty"`
    33  	Token                 string   `json:"token,omitempty"`
    34  	UploadURL             string   `json:"uploadUrl,omitempty"`
    35  	Version               string   `json:"version,omitempty"`
    36  }
    37  
    38  // GithubPublishReleaseCommand Publish a release in GitHub
    39  func GithubPublishReleaseCommand() *cobra.Command {
    40  	const STEP_NAME = "githubPublishRelease"
    41  
    42  	metadata := githubPublishReleaseMetadata()
    43  	var stepConfig githubPublishReleaseOptions
    44  	var startTime time.Time
    45  	var logCollector *log.CollectorHook
    46  	var splunkClient *splunk.Splunk
    47  	telemetryClient := &telemetry.Telemetry{}
    48  
    49  	var createGithubPublishReleaseCmd = &cobra.Command{
    50  		Use:   STEP_NAME,
    51  		Short: "Publish a release in GitHub",
    52  		Long: `This step creates a tag in your GitHub repository together with a release.
    53  The release can be filled with text plus additional information like:
    54  
    55  * Closed pull request since last release
    56  * Closed issues since last release
    57  * Link to delta information showing all commits since last release
    58  
    59  The result looks like
    60  
    61  ![Example release](../images/githubRelease.png)`,
    62  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    63  			startTime = time.Now()
    64  			log.SetStepName(STEP_NAME)
    65  			log.SetVerbose(GeneralConfig.Verbose)
    66  
    67  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    68  
    69  			path, _ := os.Getwd()
    70  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    71  			log.RegisterHook(fatalHook)
    72  
    73  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    74  			if err != nil {
    75  				log.SetErrorCategory(log.ErrorConfiguration)
    76  				return err
    77  			}
    78  			log.RegisterSecret(stepConfig.Token)
    79  
    80  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    81  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    82  				log.RegisterHook(&sentryHook)
    83  			}
    84  
    85  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    86  				splunkClient = &splunk.Splunk{}
    87  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    88  				log.RegisterHook(logCollector)
    89  			}
    90  
    91  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
    92  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
    93  			}
    94  
    95  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    96  			if err != nil {
    97  				return err
    98  			}
    99  			if err = validation.ValidateStruct(stepConfig); err != nil {
   100  				log.SetErrorCategory(log.ErrorConfiguration)
   101  				return err
   102  			}
   103  
   104  			return nil
   105  		},
   106  		Run: func(_ *cobra.Command, _ []string) {
   107  			stepTelemetryData := telemetry.CustomData{}
   108  			stepTelemetryData.ErrorCode = "1"
   109  			handler := func() {
   110  				config.RemoveVaultSecretFiles()
   111  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   112  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   113  				stepTelemetryData.PiperCommitHash = GitCommit
   114  				telemetryClient.SetData(&stepTelemetryData)
   115  				telemetryClient.Send()
   116  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   117  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   118  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   119  						GeneralConfig.HookConfig.SplunkConfig.Token,
   120  						GeneralConfig.HookConfig.SplunkConfig.Index,
   121  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   122  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   123  				}
   124  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   125  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   126  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   127  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   128  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   129  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   130  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   131  				}
   132  			}
   133  			log.DeferExitHandler(handler)
   134  			defer handler()
   135  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   136  			githubPublishRelease(stepConfig, &stepTelemetryData)
   137  			stepTelemetryData.ErrorCode = "0"
   138  			log.Entry().Info("SUCCESS")
   139  		},
   140  	}
   141  
   142  	addGithubPublishReleaseFlags(createGithubPublishReleaseCmd, &stepConfig)
   143  	return createGithubPublishReleaseCmd
   144  }
   145  
   146  func addGithubPublishReleaseFlags(cmd *cobra.Command, stepConfig *githubPublishReleaseOptions) {
   147  	cmd.Flags().BoolVar(&stepConfig.AddClosedIssues, "addClosedIssues", false, "If set to `true`, closed issues and merged pull-requests since the last release will added below the `releaseBodyHeader`")
   148  	cmd.Flags().BoolVar(&stepConfig.AddDeltaToLastRelease, "addDeltaToLastRelease", false, "If set to `true`, a link will be added to the release information that brings up all commits since the last release.")
   149  	cmd.Flags().StringVar(&stepConfig.APIURL, "apiUrl", `https://api.github.com`, "Set the GitHub API url.")
   150  	cmd.Flags().StringVar(&stepConfig.AssetPath, "assetPath", os.Getenv("PIPER_assetPath"), "Path to a release asset which should be uploaded to the list of release assets.")
   151  	cmd.Flags().StringSliceVar(&stepConfig.AssetPathList, "assetPathList", []string{}, "List of paths to a release asset which should be uploaded to the list of release assets.")
   152  	cmd.Flags().StringVar(&stepConfig.Commitish, "commitish", `master`, "Target git commitish for the release")
   153  	cmd.Flags().StringSliceVar(&stepConfig.ExcludeLabels, "excludeLabels", []string{}, "Allows to exclude issues with dedicated list of labels.")
   154  	cmd.Flags().StringSliceVar(&stepConfig.Labels, "labels", []string{}, "Labels to include in issue search.")
   155  	cmd.Flags().StringVar(&stepConfig.Owner, "owner", os.Getenv("PIPER_owner"), "Name of the GitHub organization.")
   156  	cmd.Flags().BoolVar(&stepConfig.PreRelease, "preRelease", false, "If set to `true` the release will be marked as Pre-release.")
   157  	cmd.Flags().StringVar(&stepConfig.ReleaseBodyHeader, "releaseBodyHeader", os.Getenv("PIPER_releaseBodyHeader"), "Content which will appear for the release.")
   158  	cmd.Flags().StringVar(&stepConfig.Repository, "repository", os.Getenv("PIPER_repository"), "Name of the GitHub repository.")
   159  	cmd.Flags().StringVar(&stepConfig.ServerURL, "serverUrl", `https://github.com`, "GitHub server url for end-user access.")
   160  	cmd.Flags().StringVar(&stepConfig.TagPrefix, "tagPrefix", ``, "Defines a prefix to be added to the tag.")
   161  	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")
   162  	cmd.Flags().StringVar(&stepConfig.UploadURL, "uploadUrl", `https://uploads.github.com`, "Set the GitHub API url.")
   163  	cmd.Flags().StringVar(&stepConfig.Version, "version", os.Getenv("PIPER_version"), "Define the version number which will be written as tag as well as release name.")
   164  
   165  	cmd.MarkFlagRequired("apiUrl")
   166  	cmd.MarkFlagRequired("owner")
   167  	cmd.MarkFlagRequired("repository")
   168  	cmd.MarkFlagRequired("serverUrl")
   169  	cmd.MarkFlagRequired("token")
   170  	cmd.MarkFlagRequired("uploadUrl")
   171  	cmd.MarkFlagRequired("version")
   172  }
   173  
   174  // retrieve step metadata
   175  func githubPublishReleaseMetadata() config.StepData {
   176  	var theMetaData = config.StepData{
   177  		Metadata: config.StepMetadata{
   178  			Name:        "githubPublishRelease",
   179  			Aliases:     []config.Alias{},
   180  			Description: "Publish a release in GitHub",
   181  		},
   182  		Spec: config.StepSpec{
   183  			Inputs: config.StepInputs{
   184  				Secrets: []config.StepSecrets{
   185  					{Name: "githubTokenCredentialsId", Description: "Jenkins 'Secret text' credentials ID containing token to authenticate to GitHub.", Type: "jenkins"},
   186  				},
   187  				Parameters: []config.StepParameters{
   188  					{
   189  						Name:        "addClosedIssues",
   190  						ResourceRef: []config.ResourceReference{},
   191  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   192  						Type:        "bool",
   193  						Mandatory:   false,
   194  						Aliases:     []config.Alias{},
   195  						Default:     false,
   196  					},
   197  					{
   198  						Name:        "addDeltaToLastRelease",
   199  						ResourceRef: []config.ResourceReference{},
   200  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   201  						Type:        "bool",
   202  						Mandatory:   false,
   203  						Aliases:     []config.Alias{},
   204  						Default:     false,
   205  					},
   206  					{
   207  						Name:        "apiUrl",
   208  						ResourceRef: []config.ResourceReference{},
   209  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   210  						Type:        "string",
   211  						Mandatory:   true,
   212  						Aliases:     []config.Alias{{Name: "githubApiUrl"}},
   213  						Default:     `https://api.github.com`,
   214  					},
   215  					{
   216  						Name:        "assetPath",
   217  						ResourceRef: []config.ResourceReference{},
   218  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   219  						Type:        "string",
   220  						Mandatory:   false,
   221  						Aliases:     []config.Alias{},
   222  						Default:     os.Getenv("PIPER_assetPath"),
   223  					},
   224  					{
   225  						Name:        "assetPathList",
   226  						ResourceRef: []config.ResourceReference{},
   227  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   228  						Type:        "[]string",
   229  						Mandatory:   false,
   230  						Aliases:     []config.Alias{},
   231  						Default:     []string{},
   232  					},
   233  					{
   234  						Name: "commitish",
   235  						ResourceRef: []config.ResourceReference{
   236  							{
   237  								Name:  "commonPipelineEnvironment",
   238  								Param: "git/headCommitId",
   239  							},
   240  						},
   241  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   242  						Type:      "string",
   243  						Mandatory: false,
   244  						Aliases:   []config.Alias{},
   245  						Default:   `master`,
   246  					},
   247  					{
   248  						Name:        "excludeLabels",
   249  						ResourceRef: []config.ResourceReference{},
   250  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   251  						Type:        "[]string",
   252  						Mandatory:   false,
   253  						Aliases:     []config.Alias{},
   254  						Default:     []string{},
   255  					},
   256  					{
   257  						Name:        "labels",
   258  						ResourceRef: []config.ResourceReference{},
   259  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   260  						Type:        "[]string",
   261  						Mandatory:   false,
   262  						Aliases:     []config.Alias{},
   263  						Default:     []string{},
   264  					},
   265  					{
   266  						Name: "owner",
   267  						ResourceRef: []config.ResourceReference{
   268  							{
   269  								Name:  "commonPipelineEnvironment",
   270  								Param: "github/owner",
   271  							},
   272  						},
   273  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   274  						Type:      "string",
   275  						Mandatory: true,
   276  						Aliases:   []config.Alias{{Name: "githubOrg"}},
   277  						Default:   os.Getenv("PIPER_owner"),
   278  					},
   279  					{
   280  						Name:        "preRelease",
   281  						ResourceRef: []config.ResourceReference{},
   282  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   283  						Type:        "bool",
   284  						Mandatory:   false,
   285  						Aliases:     []config.Alias{},
   286  						Default:     false,
   287  					},
   288  					{
   289  						Name:        "releaseBodyHeader",
   290  						ResourceRef: []config.ResourceReference{},
   291  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   292  						Type:        "string",
   293  						Mandatory:   false,
   294  						Aliases:     []config.Alias{},
   295  						Default:     os.Getenv("PIPER_releaseBodyHeader"),
   296  					},
   297  					{
   298  						Name: "repository",
   299  						ResourceRef: []config.ResourceReference{
   300  							{
   301  								Name:  "commonPipelineEnvironment",
   302  								Param: "github/repository",
   303  							},
   304  						},
   305  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   306  						Type:      "string",
   307  						Mandatory: true,
   308  						Aliases:   []config.Alias{{Name: "githubRepo"}},
   309  						Default:   os.Getenv("PIPER_repository"),
   310  					},
   311  					{
   312  						Name:        "serverUrl",
   313  						ResourceRef: []config.ResourceReference{},
   314  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   315  						Type:        "string",
   316  						Mandatory:   true,
   317  						Aliases:     []config.Alias{{Name: "githubServerUrl"}},
   318  						Default:     `https://github.com`,
   319  					},
   320  					{
   321  						Name:        "tagPrefix",
   322  						ResourceRef: []config.ResourceReference{},
   323  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   324  						Type:        "string",
   325  						Mandatory:   false,
   326  						Aliases:     []config.Alias{},
   327  						Default:     ``,
   328  					},
   329  					{
   330  						Name: "token",
   331  						ResourceRef: []config.ResourceReference{
   332  							{
   333  								Name: "githubTokenCredentialsId",
   334  								Type: "secret",
   335  							},
   336  
   337  							{
   338  								Name:    "githubVaultSecretName",
   339  								Type:    "vaultSecret",
   340  								Default: "github",
   341  							},
   342  						},
   343  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   344  						Type:      "string",
   345  						Mandatory: true,
   346  						Aliases:   []config.Alias{{Name: "githubToken"}, {Name: "access_token"}},
   347  						Default:   os.Getenv("PIPER_token"),
   348  					},
   349  					{
   350  						Name:        "uploadUrl",
   351  						ResourceRef: []config.ResourceReference{},
   352  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   353  						Type:        "string",
   354  						Mandatory:   true,
   355  						Aliases:     []config.Alias{{Name: "githubUploadUrl"}},
   356  						Default:     `https://uploads.github.com`,
   357  					},
   358  					{
   359  						Name: "version",
   360  						ResourceRef: []config.ResourceReference{
   361  							{
   362  								Name:  "commonPipelineEnvironment",
   363  								Param: "artifactVersion",
   364  							},
   365  						},
   366  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   367  						Type:      "string",
   368  						Mandatory: true,
   369  						Aliases:   []config.Alias{},
   370  						Default:   os.Getenv("PIPER_version"),
   371  					},
   372  				},
   373  			},
   374  		},
   375  	}
   376  	return theMetaData
   377  }