github.com/xgoffin/jenkins-library@v1.154.0/cmd/mavenExecuteStaticCodeChecks_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 mavenExecuteStaticCodeChecksOptions struct {
    19  	SpotBugs                     bool     `json:"spotBugs,omitempty"`
    20  	Pmd                          bool     `json:"pmd,omitempty"`
    21  	MavenModulesExcludes         []string `json:"mavenModulesExcludes,omitempty"`
    22  	SpotBugsExcludeFilterFile    string   `json:"spotBugsExcludeFilterFile,omitempty"`
    23  	SpotBugsIncludeFilterFile    string   `json:"spotBugsIncludeFilterFile,omitempty"`
    24  	SpotBugsMaxAllowedViolations int      `json:"spotBugsMaxAllowedViolations,omitempty"`
    25  	PmdFailurePriority           int      `json:"pmdFailurePriority,omitempty"`
    26  	PmdMaxAllowedViolations      int      `json:"pmdMaxAllowedViolations,omitempty"`
    27  	ProjectSettingsFile          string   `json:"projectSettingsFile,omitempty"`
    28  	GlobalSettingsFile           string   `json:"globalSettingsFile,omitempty"`
    29  	M2Path                       string   `json:"m2Path,omitempty"`
    30  	LogSuccessfulMavenTransfers  bool     `json:"logSuccessfulMavenTransfers,omitempty"`
    31  	InstallArtifacts             bool     `json:"installArtifacts,omitempty"`
    32  }
    33  
    34  // MavenExecuteStaticCodeChecksCommand Execute static code checks for Maven based projects. The plugins SpotBugs and PMD are used.
    35  func MavenExecuteStaticCodeChecksCommand() *cobra.Command {
    36  	const STEP_NAME = "mavenExecuteStaticCodeChecks"
    37  
    38  	metadata := mavenExecuteStaticCodeChecksMetadata()
    39  	var stepConfig mavenExecuteStaticCodeChecksOptions
    40  	var startTime time.Time
    41  	var logCollector *log.CollectorHook
    42  	var splunkClient *splunk.Splunk
    43  	telemetryClient := &telemetry.Telemetry{}
    44  
    45  	var createMavenExecuteStaticCodeChecksCmd = &cobra.Command{
    46  		Use:   STEP_NAME,
    47  		Short: "Execute static code checks for Maven based projects. The plugins SpotBugs and PMD are used.",
    48  		Long: `Executes Spotbugs Maven plugin as well as Pmd Maven plugin for static code checks.
    49  SpotBugs is a program to find bugs in Java programs. It looks for instances of “bug patterns” — code instances that are likely to be errors.
    50  For more information please visit https://spotbugs.readthedocs.io/en/latest/maven.html
    51  PMD is a source code analyzer. It finds common programming flaws like unused variables, empty catch blocks, unnecessary object creation, and so forth. It supports Java, JavaScript, Salesforce.com Apex and Visualforce, PLSQL, Apache Velocity, XML, XSL.
    52  For more information please visit https://pmd.github.io/.
    53  The plugins should be configured in the respective pom.xml.
    54  For SpotBugs include- and exclude filters as well as maximum allowed violations are conifgurable via .pipeline/config.yml.
    55  For PMD the failure priority and the max allowed violations are configurable via .pipeline/config.yml.`,
    56  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    57  			startTime = time.Now()
    58  			log.SetStepName(STEP_NAME)
    59  			log.SetVerbose(GeneralConfig.Verbose)
    60  
    61  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    62  
    63  			path, _ := os.Getwd()
    64  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    65  			log.RegisterHook(fatalHook)
    66  
    67  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    68  			if err != nil {
    69  				log.SetErrorCategory(log.ErrorConfiguration)
    70  				return err
    71  			}
    72  
    73  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    74  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    75  				log.RegisterHook(&sentryHook)
    76  			}
    77  
    78  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    79  				splunkClient = &splunk.Splunk{}
    80  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    81  				log.RegisterHook(logCollector)
    82  			}
    83  
    84  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    85  			if err != nil {
    86  				return err
    87  			}
    88  			if err = validation.ValidateStruct(stepConfig); err != nil {
    89  				log.SetErrorCategory(log.ErrorConfiguration)
    90  				return err
    91  			}
    92  
    93  			return nil
    94  		},
    95  		Run: func(_ *cobra.Command, _ []string) {
    96  			stepTelemetryData := telemetry.CustomData{}
    97  			stepTelemetryData.ErrorCode = "1"
    98  			handler := func() {
    99  				config.RemoveVaultSecretFiles()
   100  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   101  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   102  				stepTelemetryData.PiperCommitHash = GitCommit
   103  				telemetryClient.SetData(&stepTelemetryData)
   104  				telemetryClient.Send()
   105  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   106  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   107  				}
   108  			}
   109  			log.DeferExitHandler(handler)
   110  			defer handler()
   111  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   112  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   113  				splunkClient.Initialize(GeneralConfig.CorrelationID,
   114  					GeneralConfig.HookConfig.SplunkConfig.Dsn,
   115  					GeneralConfig.HookConfig.SplunkConfig.Token,
   116  					GeneralConfig.HookConfig.SplunkConfig.Index,
   117  					GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   118  			}
   119  			mavenExecuteStaticCodeChecks(stepConfig, &stepTelemetryData)
   120  			stepTelemetryData.ErrorCode = "0"
   121  			log.Entry().Info("SUCCESS")
   122  		},
   123  	}
   124  
   125  	addMavenExecuteStaticCodeChecksFlags(createMavenExecuteStaticCodeChecksCmd, &stepConfig)
   126  	return createMavenExecuteStaticCodeChecksCmd
   127  }
   128  
   129  func addMavenExecuteStaticCodeChecksFlags(cmd *cobra.Command, stepConfig *mavenExecuteStaticCodeChecksOptions) {
   130  	cmd.Flags().BoolVar(&stepConfig.SpotBugs, "spotBugs", true, "Parameter to turn off SpotBugs.")
   131  	cmd.Flags().BoolVar(&stepConfig.Pmd, "pmd", true, "Parameter to turn off PMD.")
   132  	cmd.Flags().StringSliceVar(&stepConfig.MavenModulesExcludes, "mavenModulesExcludes", []string{}, "Maven modules which should be excluded by the static code checks. By default the modules 'unit-tests' and 'integration-tests' will be excluded.")
   133  	cmd.Flags().StringVar(&stepConfig.SpotBugsExcludeFilterFile, "spotBugsExcludeFilterFile", os.Getenv("PIPER_spotBugsExcludeFilterFile"), "Path to a filter file with bug definitions which should be excluded.")
   134  	cmd.Flags().StringVar(&stepConfig.SpotBugsIncludeFilterFile, "spotBugsIncludeFilterFile", os.Getenv("PIPER_spotBugsIncludeFilterFile"), "Path to a filter file with bug definitions which should be included.")
   135  	cmd.Flags().IntVar(&stepConfig.SpotBugsMaxAllowedViolations, "spotBugsMaxAllowedViolations", 0, "The maximum number of failures allowed before execution fails.")
   136  	cmd.Flags().IntVar(&stepConfig.PmdFailurePriority, "pmdFailurePriority", 0, "What priority level to fail the build on. PMD violations are assigned a priority from 1 (most severe) to 5 (least severe) according the the rule's priority. Violations at or less than this priority level are considered failures and will fail the build if failOnViolation=true and the count exceeds maxAllowedViolations. The other violations will be regarded as warnings and will be displayed in the build output if verbose=true. Setting a value of 5 will treat all violations as failures, which may cause the build to fail. Setting a value of 1 will treat all violations as warnings. Only values from 1 to 5 are valid.")
   137  	cmd.Flags().IntVar(&stepConfig.PmdMaxAllowedViolations, "pmdMaxAllowedViolations", 0, "The maximum number of failures allowed before execution fails. Used in conjunction with failOnViolation=true and utilizes failurePriority. This value has no meaning if failOnViolation=false. If the number of failures is greater than this number, the build will be failed. If the number of failures is less than or equal to this value, then the build will not be failed.")
   138  	cmd.Flags().StringVar(&stepConfig.ProjectSettingsFile, "projectSettingsFile", os.Getenv("PIPER_projectSettingsFile"), "Path to the mvn settings file that should be used as project settings file.")
   139  	cmd.Flags().StringVar(&stepConfig.GlobalSettingsFile, "globalSettingsFile", os.Getenv("PIPER_globalSettingsFile"), "Path to the mvn settings file that should be used as global settings file.")
   140  	cmd.Flags().StringVar(&stepConfig.M2Path, "m2Path", os.Getenv("PIPER_m2Path"), "Path to the location of the local repository that should be used.")
   141  	cmd.Flags().BoolVar(&stepConfig.LogSuccessfulMavenTransfers, "logSuccessfulMavenTransfers", false, "Configures maven to log successful downloads. This is set to `false` by default to reduce the noise in build logs.")
   142  	cmd.Flags().BoolVar(&stepConfig.InstallArtifacts, "installArtifacts", false, "If enabled, it will install all artifacts to the local maven repository to make them available before running the static code checks. This is required if any maven module has dependencies to other modules in the repository and they were not installed before.")
   143  
   144  }
   145  
   146  // retrieve step metadata
   147  func mavenExecuteStaticCodeChecksMetadata() config.StepData {
   148  	var theMetaData = config.StepData{
   149  		Metadata: config.StepMetadata{
   150  			Name:        "mavenExecuteStaticCodeChecks",
   151  			Aliases:     []config.Alias{{Name: "mavenExecute", Deprecated: false}},
   152  			Description: "Execute static code checks for Maven based projects. The plugins SpotBugs and PMD are used.",
   153  		},
   154  		Spec: config.StepSpec{
   155  			Inputs: config.StepInputs{
   156  				Parameters: []config.StepParameters{
   157  					{
   158  						Name:        "spotBugs",
   159  						ResourceRef: []config.ResourceReference{},
   160  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   161  						Type:        "bool",
   162  						Mandatory:   false,
   163  						Aliases:     []config.Alias{},
   164  						Default:     true,
   165  					},
   166  					{
   167  						Name:        "pmd",
   168  						ResourceRef: []config.ResourceReference{},
   169  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   170  						Type:        "bool",
   171  						Mandatory:   false,
   172  						Aliases:     []config.Alias{},
   173  						Default:     true,
   174  					},
   175  					{
   176  						Name:        "mavenModulesExcludes",
   177  						ResourceRef: []config.ResourceReference{},
   178  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   179  						Type:        "[]string",
   180  						Mandatory:   false,
   181  						Aliases:     []config.Alias{},
   182  						Default:     []string{},
   183  					},
   184  					{
   185  						Name:        "spotBugsExcludeFilterFile",
   186  						ResourceRef: []config.ResourceReference{},
   187  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   188  						Type:        "string",
   189  						Mandatory:   false,
   190  						Aliases:     []config.Alias{{Name: "spotBugs/excludeFilterFile"}},
   191  						Default:     os.Getenv("PIPER_spotBugsExcludeFilterFile"),
   192  					},
   193  					{
   194  						Name:        "spotBugsIncludeFilterFile",
   195  						ResourceRef: []config.ResourceReference{},
   196  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   197  						Type:        "string",
   198  						Mandatory:   false,
   199  						Aliases:     []config.Alias{{Name: "spotBugs/includeFilterFile"}},
   200  						Default:     os.Getenv("PIPER_spotBugsIncludeFilterFile"),
   201  					},
   202  					{
   203  						Name:        "spotBugsMaxAllowedViolations",
   204  						ResourceRef: []config.ResourceReference{},
   205  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   206  						Type:        "int",
   207  						Mandatory:   false,
   208  						Aliases:     []config.Alias{{Name: "spotBugs/maxAllowedViolations"}},
   209  						Default:     0,
   210  					},
   211  					{
   212  						Name:        "pmdFailurePriority",
   213  						ResourceRef: []config.ResourceReference{},
   214  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   215  						Type:        "int",
   216  						Mandatory:   false,
   217  						Aliases:     []config.Alias{{Name: "pmd/failurePriority"}},
   218  						Default:     0,
   219  					},
   220  					{
   221  						Name:        "pmdMaxAllowedViolations",
   222  						ResourceRef: []config.ResourceReference{},
   223  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   224  						Type:        "int",
   225  						Mandatory:   false,
   226  						Aliases:     []config.Alias{{Name: "pmd/maxAllowedViolations"}},
   227  						Default:     0,
   228  					},
   229  					{
   230  						Name:        "projectSettingsFile",
   231  						ResourceRef: []config.ResourceReference{},
   232  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   233  						Type:        "string",
   234  						Mandatory:   false,
   235  						Aliases:     []config.Alias{{Name: "maven/projectSettingsFile"}},
   236  						Default:     os.Getenv("PIPER_projectSettingsFile"),
   237  					},
   238  					{
   239  						Name:        "globalSettingsFile",
   240  						ResourceRef: []config.ResourceReference{},
   241  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   242  						Type:        "string",
   243  						Mandatory:   false,
   244  						Aliases:     []config.Alias{{Name: "maven/globalSettingsFile"}},
   245  						Default:     os.Getenv("PIPER_globalSettingsFile"),
   246  					},
   247  					{
   248  						Name:        "m2Path",
   249  						ResourceRef: []config.ResourceReference{},
   250  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   251  						Type:        "string",
   252  						Mandatory:   false,
   253  						Aliases:     []config.Alias{{Name: "maven/m2Path"}},
   254  						Default:     os.Getenv("PIPER_m2Path"),
   255  					},
   256  					{
   257  						Name:        "logSuccessfulMavenTransfers",
   258  						ResourceRef: []config.ResourceReference{},
   259  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   260  						Type:        "bool",
   261  						Mandatory:   false,
   262  						Aliases:     []config.Alias{{Name: "maven/logSuccessfulMavenTransfers"}},
   263  						Default:     false,
   264  					},
   265  					{
   266  						Name:        "installArtifacts",
   267  						ResourceRef: []config.ResourceReference{},
   268  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   269  						Type:        "bool",
   270  						Mandatory:   false,
   271  						Aliases:     []config.Alias{},
   272  						Default:     false,
   273  					},
   274  				},
   275  			},
   276  			Containers: []config.Container{
   277  				{Name: "mvn", Image: "maven:3.6-jdk-8"},
   278  			},
   279  		},
   280  	}
   281  	return theMetaData
   282  }