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