1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2025-02-21 19:48:53 +02:00

Add groovy wrapper for mavenExecuteStaticCodeChecks and rename go step

This commit is contained in:
Florian Geckeler 2020-03-12 15:45:57 +01:00 committed by GitHub
parent dd67be3d21
commit 9a28e12d5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 167 additions and 43 deletions

View File

@ -9,7 +9,7 @@ import (
"github.com/SAP/jenkins-library/pkg/telemetry"
)
func mavenStaticCodeChecks(config mavenStaticCodeChecksOptions, telemetryData *telemetry.CustomData) {
func mavenExecuteStaticCodeChecks(config mavenExecuteStaticCodeChecksOptions, telemetryData *telemetry.CustomData) {
c := command.Command{}
c.Stdout(log.Entry().Writer())
c.Stderr(log.Entry().Writer())
@ -19,7 +19,7 @@ func mavenStaticCodeChecks(config mavenStaticCodeChecksOptions, telemetryData *t
}
}
func runMavenStaticCodeChecks(config *mavenStaticCodeChecksOptions, telemetryData *telemetry.CustomData, command execRunner) error {
func runMavenStaticCodeChecks(config *mavenExecuteStaticCodeChecksOptions, telemetryData *telemetry.CustomData, command execRunner) error {
var defines []string
var goals []string
@ -55,7 +55,7 @@ func runMavenStaticCodeChecks(config *mavenStaticCodeChecksOptions, telemetryDat
return err
}
func getSpotBugsMavenParameters(config *mavenStaticCodeChecksOptions) *maven.ExecuteOptions {
func getSpotBugsMavenParameters(config *mavenExecuteStaticCodeChecksOptions) *maven.ExecuteOptions {
var defines []string
if config.SpotBugsIncludeFilterFile != "" {
defines = append(defines, "-Dspotbugs.includeFilterFile="+config.SpotBugsIncludeFilterFile)
@ -72,7 +72,7 @@ func getSpotBugsMavenParameters(config *mavenStaticCodeChecksOptions) *maven.Exe
return &mavenOptions
}
func getPmdMavenParameters(config *mavenStaticCodeChecksOptions) *maven.ExecuteOptions {
func getPmdMavenParameters(config *mavenExecuteStaticCodeChecksOptions) *maven.ExecuteOptions {
var defines []string
if config.PmdExcludes != nil {
defines = append(defines, "-Dpmd.excludes="+strings.Join(config.PmdExcludes, ","))

View File

@ -13,7 +13,7 @@ import (
"github.com/spf13/cobra"
)
type mavenStaticCodeChecksOptions struct {
type mavenExecuteStaticCodeChecksOptions struct {
SpotBugs bool `json:"spotBugs,omitempty"`
Pmd bool `json:"pmd,omitempty"`
MavenModulesExcludes []string `json:"mavenModulesExcludes,omitempty"`
@ -23,14 +23,14 @@ type mavenStaticCodeChecksOptions struct {
PmdRuleSets []string `json:"pmdRuleSets,omitempty"`
}
// MavenStaticCodeChecksCommand Execute static code checks for Maven based projects. The plugins SpotBugs and PMD are used.
func MavenStaticCodeChecksCommand() *cobra.Command {
metadata := mavenStaticCodeChecksMetadata()
var stepConfig mavenStaticCodeChecksOptions
// MavenExecuteStaticCodeChecksCommand Execute static code checks for Maven based projects. The plugins SpotBugs and PMD are used.
func MavenExecuteStaticCodeChecksCommand() *cobra.Command {
metadata := mavenExecuteStaticCodeChecksMetadata()
var stepConfig mavenExecuteStaticCodeChecksOptions
var startTime time.Time
var createMavenStaticCodeChecksCmd = &cobra.Command{
Use: "mavenStaticCodeChecks",
var createMavenExecuteStaticCodeChecksCmd = &cobra.Command{
Use: "mavenExecuteStaticCodeChecks",
Short: "Execute static code checks for Maven based projects. The plugins SpotBugs and PMD are used.",
Long: `Executes Spotbugs Maven plugin as well as Pmd Maven plugin for static code checks.
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.
@ -39,9 +39,9 @@ PMD is a source code analyzer. It finds common programming flaws like unused var
For more information please visit https://pmd.github.io/`,
PreRunE: func(cmd *cobra.Command, args []string) error {
startTime = time.Now()
log.SetStepName("mavenStaticCodeChecks")
log.SetStepName("mavenExecuteStaticCodeChecks")
log.SetVerbose(GeneralConfig.Verbose)
return PrepareConfig(cmd, &metadata, "mavenStaticCodeChecks", &stepConfig, config.OpenPiperFile)
return PrepareConfig(cmd, &metadata, "mavenExecuteStaticCodeChecks", &stepConfig, config.OpenPiperFile)
},
Run: func(cmd *cobra.Command, args []string) {
telemetryData := telemetry.CustomData{}
@ -52,17 +52,17 @@ For more information please visit https://pmd.github.io/`,
}
log.DeferExitHandler(handler)
defer handler()
telemetry.Initialize(GeneralConfig.NoTelemetry, "mavenStaticCodeChecks")
mavenStaticCodeChecks(stepConfig, &telemetryData)
telemetry.Initialize(GeneralConfig.NoTelemetry, "mavenExecuteStaticCodeChecks")
mavenExecuteStaticCodeChecks(stepConfig, &telemetryData)
telemetryData.ErrorCode = "0"
},
}
addMavenStaticCodeChecksFlags(createMavenStaticCodeChecksCmd, &stepConfig)
return createMavenStaticCodeChecksCmd
addMavenExecuteStaticCodeChecksFlags(createMavenExecuteStaticCodeChecksCmd, &stepConfig)
return createMavenExecuteStaticCodeChecksCmd
}
func addMavenStaticCodeChecksFlags(cmd *cobra.Command, stepConfig *mavenStaticCodeChecksOptions) {
func addMavenExecuteStaticCodeChecksFlags(cmd *cobra.Command, stepConfig *mavenExecuteStaticCodeChecksOptions) {
cmd.Flags().BoolVar(&stepConfig.SpotBugs, "spotBugs", true, "Parameter to turn off SpotBugs.")
cmd.Flags().BoolVar(&stepConfig.Pmd, "pmd", true, "Parameter to turn off PMD.")
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.")
@ -74,7 +74,7 @@ func addMavenStaticCodeChecksFlags(cmd *cobra.Command, stepConfig *mavenStaticCo
}
// retrieve step metadata
func mavenStaticCodeChecksMetadata() config.StepData {
func mavenExecuteStaticCodeChecksMetadata() config.StepData {
var theMetaData = config.StepData{
Spec: config.StepSpec{
Inputs: config.StepInputs{

View File

@ -0,0 +1,16 @@
package cmd
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMavenExecuteStaticCodeChecksCommand(t *testing.T) {
testCmd := MavenExecuteStaticCodeChecksCommand()
// only high level testing performed - details are tested in step generation procudure
assert.Equal(t, "mavenExecuteStaticCodeChecks", testCmd.Use, "command name incorrect")
}

View File

@ -15,7 +15,7 @@ import (
func TestRunMavenStaticCodeChecks(t *testing.T) {
t.Run("should run spotBugs and pmd with all configured options", func(t *testing.T) {
execMockRunner := mock.ExecMockRunner{}
config := mavenStaticCodeChecksOptions{
config := mavenExecuteStaticCodeChecksOptions{
SpotBugs: true,
Pmd: true,
PmdExcludes: []string{"*test.java", "*prod.java"},
@ -54,7 +54,7 @@ func TestRunMavenStaticCodeChecks(t *testing.T) {
var hasFailed bool
log.Entry().Logger.ExitFunc = func(int) { hasFailed = true }
execMockRunner := mock.ExecMockRunner{}
config := mavenStaticCodeChecksOptions{
config := mavenExecuteStaticCodeChecksOptions{
SpotBugs: false,
Pmd: false,
}
@ -65,7 +65,7 @@ func TestRunMavenStaticCodeChecks(t *testing.T) {
func TestGetPmdMavenParameters(t *testing.T) {
t.Run("should return maven options with excludes and rulesets", func(t *testing.T) {
config := mavenStaticCodeChecksOptions{
config := mavenExecuteStaticCodeChecksOptions{
Pmd: true,
PmdExcludes: []string{"*test.java", "*prod.java"},
PmdRuleSets: []string{"myRule.xml", "anotherRule.xml"},
@ -78,7 +78,7 @@ func TestGetPmdMavenParameters(t *testing.T) {
assert.Equal(t, &expected, getPmdMavenParameters(&config))
})
t.Run("should return maven goal only", func(t *testing.T) {
config := mavenStaticCodeChecksOptions{}
config := mavenExecuteStaticCodeChecksOptions{}
expected := maven.ExecuteOptions{
Goals: []string{"org.apache.maven.plugins:maven-pmd-plugin:3.13.0:pmd"}}
@ -88,7 +88,7 @@ func TestGetPmdMavenParameters(t *testing.T) {
func TestGetSpotBugsMavenParameters(t *testing.T) {
t.Run("should return maven options with excludes and include filters", func(t *testing.T) {
config := mavenStaticCodeChecksOptions{
config := mavenExecuteStaticCodeChecksOptions{
SpotBugs: true,
SpotBugsExcludeFilterFile: "excludeFilter.xml",
SpotBugsIncludeFilterFile: "includeFilter.xml",
@ -101,7 +101,7 @@ func TestGetSpotBugsMavenParameters(t *testing.T) {
assert.Equal(t, &expected, getSpotBugsMavenParameters(&config))
})
t.Run("should return maven goal only", func(t *testing.T) {
config := mavenStaticCodeChecksOptions{}
config := mavenExecuteStaticCodeChecksOptions{}
expected := maven.ExecuteOptions{
Goals: []string{"com.github.spotbugs:spotbugs-maven-plugin:3.1.12:spotbugs"}}

View File

@ -1,16 +0,0 @@
package cmd
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMavenStaticCodeChecksCommand(t *testing.T) {
testCmd := MavenStaticCodeChecksCommand()
// only high level testing performed - details are tested in step generation procudure
assert.Equal(t, "mavenStaticCodeChecks", testCmd.Use, "command name incorrect")
}

View File

@ -59,7 +59,7 @@ func Execute() {
rootCmd.AddCommand(MtaBuildCommand())
rootCmd.AddCommand(ProtecodeExecuteScanCommand())
rootCmd.AddCommand(MavenExecuteCommand())
rootCmd.AddCommand(MavenStaticCodeChecksCommand())
rootCmd.AddCommand(MavenExecuteStaticCodeChecksCommand())
addRootFlags(rootCmd)
if err := rootCmd.Execute(); err != nil {

View File

@ -1,5 +1,5 @@
metadata:
name: mavenStaticCodeChecks
name: mavenExecuteStaticCodeChecks
description: Execute static code checks for Maven based projects. The plugins SpotBugs and PMD are used.
longDescription: |
Executes Spotbugs Maven plugin as well as Pmd Maven plugin for static code checks.
@ -69,3 +69,7 @@ spec:
- STEPS
aliases:
- name: pmd/ruleSets
containers:
- name: mvn
image: maven:3.6-jdk-8
imagePullPolicy: Never

View File

@ -122,6 +122,7 @@ public class CommonStepsTest extends BasePiperTest{
'protecodeExecuteScan', //implementing new golang pattern without fields
'xsDeploy', //implementing new golang pattern without fields
'cloudFoundryDeleteService', //implementing new golang pattern without fields
'mavenExecuteStaticCodeChecks', //implementing new golang pattern without fields
]
@Test

View File

@ -0,0 +1,72 @@
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.junit.rules.RuleChain
import util.BasePiperTest
import util.JenkinsCredentialsRule
import util.JenkinsFileExistsRule
import util.JenkinsReadJsonRule
import util.JenkinsReadYamlRule
import util.JenkinsShellCallRule
import util.JenkinsStepRule
import util.JenkinsWriteFileRule
import util.Rules
import static org.hamcrest.Matchers.allOf
import static org.hamcrest.Matchers.containsString
import static org.hamcrest.Matchers.is
import static org.hamcrest.Matchers.startsWith
import static org.junit.Assert.assertThat
class MavenExecuteStaticCodeChecksTest extends BasePiperTest {
private ExpectedException exception = ExpectedException.none()
private JenkinsCredentialsRule credentialsRule = new JenkinsCredentialsRule(this)
private JenkinsReadJsonRule readJsonRule = new JenkinsReadJsonRule(this)
private JenkinsShellCallRule shellCallRule = new JenkinsShellCallRule(this)
private JenkinsStepRule stepRule = new JenkinsStepRule(this)
private JenkinsWriteFileRule writeFileRule = new JenkinsWriteFileRule(this)
private JenkinsFileExistsRule fileExistsRule = new JenkinsFileExistsRule(this, [])
private List withEnvArgs = []
@Rule
public RuleChain rules = Rules
.getCommonRules(this)
.around(exception)
.around(new JenkinsReadYamlRule(this))
.around(credentialsRule)
.around(readJsonRule)
.around(shellCallRule)
.around(stepRule)
.around(writeFileRule)
.around(fileExistsRule)
@Before
void init() {
helper.registerAllowedMethod("withEnv", [List.class, Closure.class], { arguments, closure ->
arguments.each { arg ->
withEnvArgs.add(arg.toString())
}
return closure()
})
helper.registerAllowedMethod("dockerExecute", [Map.class, Closure.class], {
Map params, Closure c ->
c.call()
})
shellCallRule.setReturnValue('./piper getConfig --contextConfig --stepMetadata \'.pipeline/metadata/mavenStaticCodeChecks.yaml\'', '{"dockerImage": "maven:3.6-jdk-8"}')
}
@Test
void testMavenExecuteStaticCodeChecksDefault() {
stepRule.step.mavenExecuteStaticCodeChecks(
juStabUtils: utils,
jenkinsUtilsStub: jenkinsUtils,
testParam: "This is test content",
script: nullScript
)
// asserts
assertThat(writeFileRule.files['.pipeline/metadata/mavenStaticCodeChecks.yaml'], containsString('name: mavenExecuteStaticCodeChecks'))
assertThat(withEnvArgs[0], allOf(startsWith('PIPER_parametersJSON'), containsString('"testParam":"This is test content"')))
assertThat(shellCallRule.shell[1], is('./piper mavenExecuteStaticCodeChecks'))
}
}

View File

@ -0,0 +1,47 @@
import com.sap.piper.PiperGoUtils
import com.sap.piper.Utils
import groovy.transform.Field
import static com.sap.piper.Prerequisites.checkScript
@Field String METADATA_FILE = 'metadata/mavenStaticCodeChecks.yaml'
@Field String STEP_NAME = getClass().getName()
@Field String METADATA_FOLDER = '.pipeline' // metadata file contains already the "metadata" folder level, hence we end up in a folder ".pipeline/metadata"
void call(Map parameters = [:]) {
handlePipelineStepErrors(stepName: STEP_NAME, stepParameters: parameters) {
final script = checkScript(this, parameters) ?: null
if (!script) {
error "Reference to surrounding pipeline script not provided (script: this)."
}
def utils = parameters.juStabUtils ?: new Utils()
new PiperGoUtils(this, utils).unstashPiperBin()
// Make a shallow copy of the passed-in Map in order to prevent removal of top-level keys
// to be visible in calling code, just in case the map is still used there.
parameters = [:] << parameters
// do not forward these parameters to the go layer
parameters.remove('juStabUtils')
parameters.remove('piperGoUtils')
parameters.remove('script')
script.commonPipelineEnvironment.writeToDisk(script)
writeFile(file: "${METADATA_FOLDER}/${METADATA_FILE}", text: libraryResource(METADATA_FILE))
withEnv([
"PIPER_parametersJSON=${groovy.json.JsonOutput.toJson(parameters)}",
]) {
// get context configuration
Map contextConfig = readJSON(text: sh(returnStdout: true, script: "./piper getConfig --contextConfig --stepMetadata '${METADATA_FOLDER}/${METADATA_FILE}'"))
dockerExecute([script: script].plus([dockerImage: contextConfig.dockerImage])) {
sh "./piper mavenExecuteStaticCodeChecks"
}
}
}
}