github.com/SAP/jenkins-library@v1.362.0/cmd/gradleExecuteBuild_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  	"path/filepath"
     9  	"reflect"
    10  	"strings"
    11  	"time"
    12  
    13  	"github.com/SAP/jenkins-library/pkg/config"
    14  	"github.com/SAP/jenkins-library/pkg/gcs"
    15  	"github.com/SAP/jenkins-library/pkg/log"
    16  	"github.com/SAP/jenkins-library/pkg/piperenv"
    17  	"github.com/SAP/jenkins-library/pkg/splunk"
    18  	"github.com/SAP/jenkins-library/pkg/telemetry"
    19  	"github.com/SAP/jenkins-library/pkg/validation"
    20  	"github.com/bmatcuk/doublestar"
    21  	"github.com/spf13/cobra"
    22  )
    23  
    24  type gradleExecuteBuildOptions struct {
    25  	Path                          string   `json:"path,omitempty"`
    26  	Task                          string   `json:"task,omitempty"`
    27  	Publish                       bool     `json:"publish,omitempty"`
    28  	RepositoryURL                 string   `json:"repositoryUrl,omitempty"`
    29  	RepositoryPassword            string   `json:"repositoryPassword,omitempty"`
    30  	RepositoryUsername            string   `json:"repositoryUsername,omitempty"`
    31  	CreateBOM                     bool     `json:"createBOM,omitempty"`
    32  	ArtifactVersion               string   `json:"artifactVersion,omitempty"`
    33  	ArtifactGroupID               string   `json:"artifactGroupId,omitempty"`
    34  	ArtifactID                    string   `json:"artifactId,omitempty"`
    35  	UseWrapper                    bool     `json:"useWrapper,omitempty"`
    36  	ApplyPublishingForAllProjects bool     `json:"applyPublishingForAllProjects,omitempty"`
    37  	ExcludeCreateBOMForProjects   []string `json:"excludeCreateBOMForProjects,omitempty"`
    38  	ExcludePublishingForProjects  []string `json:"excludePublishingForProjects,omitempty"`
    39  	BuildFlags                    []string `json:"buildFlags,omitempty"`
    40  }
    41  
    42  type gradleExecuteBuildReports struct {
    43  }
    44  
    45  func (p *gradleExecuteBuildReports) persist(stepConfig gradleExecuteBuildOptions, gcpJsonKeyFilePath string, gcsBucketId string, gcsFolderPath string, gcsSubFolder string) {
    46  	if gcsBucketId == "" {
    47  		log.Entry().Info("persisting reports to GCS is disabled, because gcsBucketId is empty")
    48  		return
    49  	}
    50  	log.Entry().Info("Uploading reports to Google Cloud Storage...")
    51  	content := []gcs.ReportOutputParam{
    52  		{FilePattern: "**/bom-gradle.xml", ParamRef: "", StepResultType: "sbom"},
    53  	}
    54  	envVars := []gcs.EnvVar{
    55  		{Name: "GOOGLE_APPLICATION_CREDENTIALS", Value: gcpJsonKeyFilePath, Modified: false},
    56  	}
    57  	gcsClient, err := gcs.NewClient(gcs.WithEnvVars(envVars))
    58  	if err != nil {
    59  		log.Entry().Errorf("creation of GCS client failed: %v", err)
    60  		return
    61  	}
    62  	defer gcsClient.Close()
    63  	structVal := reflect.ValueOf(&stepConfig).Elem()
    64  	inputParameters := map[string]string{}
    65  	for i := 0; i < structVal.NumField(); i++ {
    66  		field := structVal.Type().Field(i)
    67  		if field.Type.String() == "string" {
    68  			paramName := strings.Split(field.Tag.Get("json"), ",")
    69  			paramValue, _ := structVal.Field(i).Interface().(string)
    70  			inputParameters[paramName[0]] = paramValue
    71  		}
    72  	}
    73  	if err := gcs.PersistReportsToGCS(gcsClient, content, inputParameters, gcsFolderPath, gcsBucketId, gcsSubFolder, doublestar.Glob, os.Stat); err != nil {
    74  		log.Entry().Errorf("failed to persist reports: %v", err)
    75  	}
    76  }
    77  
    78  type gradleExecuteBuildCommonPipelineEnvironment struct {
    79  	custom struct {
    80  		artifacts piperenv.Artifacts
    81  	}
    82  }
    83  
    84  func (p *gradleExecuteBuildCommonPipelineEnvironment) persist(path, resourceName string) {
    85  	content := []struct {
    86  		category string
    87  		name     string
    88  		value    interface{}
    89  	}{
    90  		{category: "custom", name: "artifacts", value: p.custom.artifacts},
    91  	}
    92  
    93  	errCount := 0
    94  	for _, param := range content {
    95  		err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(param.category, param.name), param.value)
    96  		if err != nil {
    97  			log.Entry().WithError(err).Error("Error persisting piper environment.")
    98  			errCount++
    99  		}
   100  	}
   101  	if errCount > 0 {
   102  		log.Entry().Error("failed to persist Piper environment")
   103  	}
   104  }
   105  
   106  // GradleExecuteBuildCommand This step runs a gradle build command with parameters provided to the step.
   107  func GradleExecuteBuildCommand() *cobra.Command {
   108  	const STEP_NAME = "gradleExecuteBuild"
   109  
   110  	metadata := gradleExecuteBuildMetadata()
   111  	var stepConfig gradleExecuteBuildOptions
   112  	var startTime time.Time
   113  	var reports gradleExecuteBuildReports
   114  	var commonPipelineEnvironment gradleExecuteBuildCommonPipelineEnvironment
   115  	var logCollector *log.CollectorHook
   116  	var splunkClient *splunk.Splunk
   117  	telemetryClient := &telemetry.Telemetry{}
   118  
   119  	var createGradleExecuteBuildCmd = &cobra.Command{
   120  		Use:   STEP_NAME,
   121  		Short: "This step runs a gradle build command with parameters provided to the step.",
   122  		Long:  `This step runs a gradle build command with parameters provided to the step.Supports execution of gradle tasks with or without wrapper.Gradle tasks and flags can be specified via 'task' or 'buildFlags' parameter. If both are not specified 'build' task will run by default.`,
   123  		PreRunE: func(cmd *cobra.Command, _ []string) error {
   124  			startTime = time.Now()
   125  			log.SetStepName(STEP_NAME)
   126  			log.SetVerbose(GeneralConfig.Verbose)
   127  
   128  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
   129  
   130  			path, _ := os.Getwd()
   131  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
   132  			log.RegisterHook(fatalHook)
   133  
   134  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
   135  			if err != nil {
   136  				log.SetErrorCategory(log.ErrorConfiguration)
   137  				return err
   138  			}
   139  			log.RegisterSecret(stepConfig.RepositoryPassword)
   140  			log.RegisterSecret(stepConfig.RepositoryUsername)
   141  
   142  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
   143  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
   144  				log.RegisterHook(&sentryHook)
   145  			}
   146  
   147  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   148  				splunkClient = &splunk.Splunk{}
   149  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   150  				log.RegisterHook(logCollector)
   151  			}
   152  
   153  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
   154  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
   155  			}
   156  
   157  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   158  			if err != nil {
   159  				return err
   160  			}
   161  			if err = validation.ValidateStruct(stepConfig); err != nil {
   162  				log.SetErrorCategory(log.ErrorConfiguration)
   163  				return err
   164  			}
   165  
   166  			return nil
   167  		},
   168  		Run: func(_ *cobra.Command, _ []string) {
   169  			stepTelemetryData := telemetry.CustomData{}
   170  			stepTelemetryData.ErrorCode = "1"
   171  			handler := func() {
   172  				reports.persist(stepConfig, GeneralConfig.GCPJsonKeyFilePath, GeneralConfig.GCSBucketId, GeneralConfig.GCSFolderPath, GeneralConfig.GCSSubFolder)
   173  				commonPipelineEnvironment.persist(GeneralConfig.EnvRootPath, "commonPipelineEnvironment")
   174  				config.RemoveVaultSecretFiles()
   175  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   176  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   177  				stepTelemetryData.PiperCommitHash = GitCommit
   178  				telemetryClient.SetData(&stepTelemetryData)
   179  				telemetryClient.Send()
   180  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   181  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   182  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   183  						GeneralConfig.HookConfig.SplunkConfig.Token,
   184  						GeneralConfig.HookConfig.SplunkConfig.Index,
   185  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   186  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   187  				}
   188  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   189  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   190  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   191  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   192  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   193  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   194  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   195  				}
   196  			}
   197  			log.DeferExitHandler(handler)
   198  			defer handler()
   199  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token)
   200  			gradleExecuteBuild(stepConfig, &stepTelemetryData, &commonPipelineEnvironment)
   201  			stepTelemetryData.ErrorCode = "0"
   202  			log.Entry().Info("SUCCESS")
   203  		},
   204  	}
   205  
   206  	addGradleExecuteBuildFlags(createGradleExecuteBuildCmd, &stepConfig)
   207  	return createGradleExecuteBuildCmd
   208  }
   209  
   210  func addGradleExecuteBuildFlags(cmd *cobra.Command, stepConfig *gradleExecuteBuildOptions) {
   211  	cmd.Flags().StringVar(&stepConfig.Path, "path", os.Getenv("PIPER_path"), "Path to the folder with build.gradle (or build.gradle.kts) file which should be executed.")
   212  	cmd.Flags().StringVar(&stepConfig.Task, "task", `build`, "A single gradle task that should be executed. If you prefer more than one, use 'buildFlags' parameter. If 'buildFlags' parameter is specified, this parameter will be ignored.")
   213  	cmd.Flags().BoolVar(&stepConfig.Publish, "publish", false, "Configures gradle to publish the artifact to a repository.")
   214  	cmd.Flags().StringVar(&stepConfig.RepositoryURL, "repositoryUrl", os.Getenv("PIPER_repositoryUrl"), "Url to the repository to which the project artifacts should be published.")
   215  	cmd.Flags().StringVar(&stepConfig.RepositoryPassword, "repositoryPassword", os.Getenv("PIPER_repositoryPassword"), "Password for the repository to which the project artifacts should be published.")
   216  	cmd.Flags().StringVar(&stepConfig.RepositoryUsername, "repositoryUsername", os.Getenv("PIPER_repositoryUsername"), "Username for the repository to which the project artifacts should be published.")
   217  	cmd.Flags().BoolVar(&stepConfig.CreateBOM, "createBOM", false, "Creates the bill of materials (BOM) using CycloneDX plugin.")
   218  	cmd.Flags().StringVar(&stepConfig.ArtifactVersion, "artifactVersion", os.Getenv("PIPER_artifactVersion"), "Version of the artifact to be built.")
   219  	cmd.Flags().StringVar(&stepConfig.ArtifactGroupID, "artifactGroupId", os.Getenv("PIPER_artifactGroupId"), "The group of the artifact.")
   220  	cmd.Flags().StringVar(&stepConfig.ArtifactID, "artifactId", os.Getenv("PIPER_artifactId"), "The name of the artifact.")
   221  	cmd.Flags().BoolVar(&stepConfig.UseWrapper, "useWrapper", false, "If set to false all commands are executed using 'gradle', otherwise 'gradlew' is executed.")
   222  	cmd.Flags().BoolVar(&stepConfig.ApplyPublishingForAllProjects, "applyPublishingForAllProjects", false, "If set to false publishing logic will be applied in 'rootProject' directive, otherwise 'allprojects' will be directive used")
   223  	cmd.Flags().StringSliceVar(&stepConfig.ExcludeCreateBOMForProjects, "excludeCreateBOMForProjects", []string{}, "Defines which projects/subprojects will be ignored during bom creation. Only if applyCreateBOMForAllProjects is set to true")
   224  	cmd.Flags().StringSliceVar(&stepConfig.ExcludePublishingForProjects, "excludePublishingForProjects", []string{}, "Defines which projects/subprojects will be ignored during publishing. Only if applyCreateBOMForAllProjects is set to true")
   225  	cmd.Flags().StringSliceVar(&stepConfig.BuildFlags, "buildFlags", []string{}, "Defines a list of tasks and/or arguments to be provided for gradle in the respective order to be executed. This list takes precedence if specified over 'task' parameter")
   226  
   227  }
   228  
   229  // retrieve step metadata
   230  func gradleExecuteBuildMetadata() config.StepData {
   231  	var theMetaData = config.StepData{
   232  		Metadata: config.StepMetadata{
   233  			Name:        "gradleExecuteBuild",
   234  			Aliases:     []config.Alias{},
   235  			Description: "This step runs a gradle build command with parameters provided to the step.",
   236  		},
   237  		Spec: config.StepSpec{
   238  			Inputs: config.StepInputs{
   239  				Parameters: []config.StepParameters{
   240  					{
   241  						Name:        "path",
   242  						ResourceRef: []config.ResourceReference{},
   243  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   244  						Type:        "string",
   245  						Mandatory:   false,
   246  						Aliases:     []config.Alias{{Name: "buildGradlePath"}},
   247  						Default:     os.Getenv("PIPER_path"),
   248  					},
   249  					{
   250  						Name:        "task",
   251  						ResourceRef: []config.ResourceReference{},
   252  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   253  						Type:        "string",
   254  						Mandatory:   false,
   255  						Aliases:     []config.Alias{},
   256  						Default:     `build`,
   257  					},
   258  					{
   259  						Name:        "publish",
   260  						ResourceRef: []config.ResourceReference{},
   261  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   262  						Type:        "bool",
   263  						Mandatory:   false,
   264  						Aliases:     []config.Alias{},
   265  						Default:     false,
   266  					},
   267  					{
   268  						Name: "repositoryUrl",
   269  						ResourceRef: []config.ResourceReference{
   270  							{
   271  								Name:  "commonPipelineEnvironment",
   272  								Param: "custom/repositoryUrl",
   273  							},
   274  						},
   275  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   276  						Type:      "string",
   277  						Mandatory: false,
   278  						Aliases:   []config.Alias{},
   279  						Default:   os.Getenv("PIPER_repositoryUrl"),
   280  					},
   281  					{
   282  						Name: "repositoryPassword",
   283  						ResourceRef: []config.ResourceReference{
   284  							{
   285  								Name:  "commonPipelineEnvironment",
   286  								Param: "custom/repositoryPassword",
   287  							},
   288  						},
   289  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   290  						Type:      "string",
   291  						Mandatory: false,
   292  						Aliases:   []config.Alias{},
   293  						Default:   os.Getenv("PIPER_repositoryPassword"),
   294  					},
   295  					{
   296  						Name: "repositoryUsername",
   297  						ResourceRef: []config.ResourceReference{
   298  							{
   299  								Name:  "commonPipelineEnvironment",
   300  								Param: "custom/repositoryUsername",
   301  							},
   302  						},
   303  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   304  						Type:      "string",
   305  						Mandatory: false,
   306  						Aliases:   []config.Alias{},
   307  						Default:   os.Getenv("PIPER_repositoryUsername"),
   308  					},
   309  					{
   310  						Name:        "createBOM",
   311  						ResourceRef: []config.ResourceReference{},
   312  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   313  						Type:        "bool",
   314  						Mandatory:   false,
   315  						Aliases:     []config.Alias{},
   316  						Default:     false,
   317  					},
   318  					{
   319  						Name: "artifactVersion",
   320  						ResourceRef: []config.ResourceReference{
   321  							{
   322  								Name:  "commonPipelineEnvironment",
   323  								Param: "artifactVersion",
   324  							},
   325  						},
   326  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   327  						Type:      "string",
   328  						Mandatory: false,
   329  						Aliases:   []config.Alias{},
   330  						Default:   os.Getenv("PIPER_artifactVersion"),
   331  					},
   332  					{
   333  						Name: "artifactGroupId",
   334  						ResourceRef: []config.ResourceReference{
   335  							{
   336  								Name:  "commonPipelineEnvironment",
   337  								Param: "groupId",
   338  							},
   339  						},
   340  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   341  						Type:      "string",
   342  						Mandatory: false,
   343  						Aliases:   []config.Alias{},
   344  						Default:   os.Getenv("PIPER_artifactGroupId"),
   345  					},
   346  					{
   347  						Name: "artifactId",
   348  						ResourceRef: []config.ResourceReference{
   349  							{
   350  								Name:  "commonPipelineEnvironment",
   351  								Param: "artifactId",
   352  							},
   353  						},
   354  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   355  						Type:      "string",
   356  						Mandatory: false,
   357  						Aliases:   []config.Alias{},
   358  						Default:   os.Getenv("PIPER_artifactId"),
   359  					},
   360  					{
   361  						Name:        "useWrapper",
   362  						ResourceRef: []config.ResourceReference{},
   363  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   364  						Type:        "bool",
   365  						Mandatory:   false,
   366  						Aliases:     []config.Alias{},
   367  						Default:     false,
   368  					},
   369  					{
   370  						Name:        "applyPublishingForAllProjects",
   371  						ResourceRef: []config.ResourceReference{},
   372  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   373  						Type:        "bool",
   374  						Mandatory:   false,
   375  						Aliases:     []config.Alias{},
   376  						Default:     false,
   377  					},
   378  					{
   379  						Name:        "excludeCreateBOMForProjects",
   380  						ResourceRef: []config.ResourceReference{},
   381  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   382  						Type:        "[]string",
   383  						Mandatory:   false,
   384  						Aliases:     []config.Alias{},
   385  						Default:     []string{},
   386  					},
   387  					{
   388  						Name:        "excludePublishingForProjects",
   389  						ResourceRef: []config.ResourceReference{},
   390  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   391  						Type:        "[]string",
   392  						Mandatory:   false,
   393  						Aliases:     []config.Alias{},
   394  						Default:     []string{},
   395  					},
   396  					{
   397  						Name:        "buildFlags",
   398  						ResourceRef: []config.ResourceReference{},
   399  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   400  						Type:        "[]string",
   401  						Mandatory:   false,
   402  						Aliases:     []config.Alias{},
   403  						Default:     []string{},
   404  					},
   405  				},
   406  			},
   407  			Containers: []config.Container{
   408  				{Name: "gradle", Image: "gradle:6-jdk11-alpine"},
   409  			},
   410  			Outputs: config.StepOutputs{
   411  				Resources: []config.StepResources{
   412  					{
   413  						Name: "reports",
   414  						Type: "reports",
   415  						Parameters: []map[string]interface{}{
   416  							{"filePattern": "**/bom-gradle.xml", "type": "sbom"},
   417  						},
   418  					},
   419  					{
   420  						Name: "commonPipelineEnvironment",
   421  						Type: "piperEnvironment",
   422  						Parameters: []map[string]interface{}{
   423  							{"name": "custom/artifacts", "type": "piperenv.Artifacts"},
   424  						},
   425  					},
   426  				},
   427  			},
   428  		},
   429  	}
   430  	return theMetaData
   431  }