1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2025-09-16 09:26:22 +02:00

Add mavenExecute to go lib

This commit is contained in:
Florian Geckeler
2020-02-28 13:09:46 +01:00
committed by GitHub
parent 95a1a4d928
commit 783d955654
7 changed files with 509 additions and 0 deletions

32
cmd/mavenExecute.go Normal file
View File

@@ -0,0 +1,32 @@
package cmd
import (
"github.com/SAP/jenkins-library/pkg/command"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/maven"
"github.com/SAP/jenkins-library/pkg/telemetry"
)
func mavenExecute(config mavenExecuteOptions, telemetryData *telemetry.CustomData) string {
c := command.Command{}
options := maven.ExecuteOptions{
PomPath: config.PomPath,
ProjectSettingsFile: config.ProjectSettingsFile,
GlobalSettingsFile: config.GlobalSettingsFile,
M2Path: config.M2Path,
Goals: config.Goals,
Defines: config.Defines,
Flags: config.Flags,
LogSuccessfulMavenTransfers: config.LogSuccessfulMavenTransfers,
ReturnStdout: config.ReturnStdout,
}
output, err := maven.Execute(&options, &c)
if err != nil {
log.Entry().WithError(err).Fatal("step execution failed")
}
return output
}

View File

@@ -0,0 +1,160 @@
// Code generated by piper's step-generator. DO NOT EDIT.
package cmd
import (
"fmt"
"os"
"time"
"github.com/SAP/jenkins-library/pkg/config"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/telemetry"
"github.com/spf13/cobra"
)
type mavenExecuteOptions struct {
PomPath string `json:"pomPath,omitempty"`
ProjectSettingsFile string `json:"projectSettingsFile,omitempty"`
GlobalSettingsFile string `json:"globalSettingsFile,omitempty"`
M2Path string `json:"m2Path,omitempty"`
Goals []string `json:"goals,omitempty"`
Defines []string `json:"defines,omitempty"`
Flags []string `json:"flags,omitempty"`
LogSuccessfulMavenTransfers bool `json:"logSuccessfulMavenTransfers,omitempty"`
ReturnStdout bool `json:"returnStdout,omitempty"`
}
// MavenExecuteCommand This step allows to run maven commands
func MavenExecuteCommand() *cobra.Command {
metadata := mavenExecuteMetadata()
var stepConfig mavenExecuteOptions
var startTime time.Time
var createMavenExecuteCmd = &cobra.Command{
Use: "mavenExecute",
Short: "This step allows to run maven commands",
Long: `This step runs a maven command based on the parameters provided to the step.`,
PreRunE: func(cmd *cobra.Command, args []string) error {
startTime = time.Now()
log.SetStepName("mavenExecute")
log.SetVerbose(GeneralConfig.Verbose)
return PrepareConfig(cmd, &metadata, "mavenExecute", &stepConfig, config.OpenPiperFile)
},
Run: func(cmd *cobra.Command, args []string) {
telemetryData := telemetry.CustomData{}
telemetryData.ErrorCode = "1"
handler := func() {
telemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
telemetry.Send(&telemetryData)
}
log.DeferExitHandler(handler)
defer handler()
telemetry.Initialize(GeneralConfig.NoTelemetry, "mavenExecute")
mavenExecute(stepConfig, &telemetryData)
telemetryData.ErrorCode = "0"
},
}
addMavenExecuteFlags(createMavenExecuteCmd, &stepConfig)
return createMavenExecuteCmd
}
func addMavenExecuteFlags(cmd *cobra.Command, stepConfig *mavenExecuteOptions) {
cmd.Flags().StringVar(&stepConfig.PomPath, "pomPath", os.Getenv("PIPER_pomPath"), "Path to the pom file that should be used.")
cmd.Flags().StringVar(&stepConfig.ProjectSettingsFile, "projectSettingsFile", os.Getenv("PIPER_projectSettingsFile"), "Path to the mvn settings file that should be used as project settings file.")
cmd.Flags().StringVar(&stepConfig.GlobalSettingsFile, "globalSettingsFile", os.Getenv("PIPER_globalSettingsFile"), "Path to the mvn settings file that should be used as global settings file.")
cmd.Flags().StringVar(&stepConfig.M2Path, "m2Path", os.Getenv("PIPER_m2Path"), "Path to the location of the local repository that should be used.")
cmd.Flags().StringSliceVar(&stepConfig.Goals, "goals", []string{}, "Maven goals that should be executed.")
cmd.Flags().StringSliceVar(&stepConfig.Defines, "defines", []string{}, "Additional properties in form of -Dkey=value.")
cmd.Flags().StringSliceVar(&stepConfig.Flags, "flags", []string{}, "Flags to provide when running mvn.")
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.")
cmd.Flags().BoolVar(&stepConfig.ReturnStdout, "returnStdout", false, "Returns the output of the maven command for further processing.")
cmd.MarkFlagRequired("goals")
}
// retrieve step metadata
func mavenExecuteMetadata() config.StepData {
var theMetaData = config.StepData{
Spec: config.StepSpec{
Inputs: config.StepInputs{
Parameters: []config.StepParameters{
{
Name: "pomPath",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
},
{
Name: "projectSettingsFile",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
},
{
Name: "globalSettingsFile",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
},
{
Name: "m2Path",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
},
{
Name: "goals",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS"},
Type: "[]string",
Mandatory: true,
Aliases: []config.Alias{},
},
{
Name: "defines",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS"},
Type: "[]string",
Mandatory: false,
Aliases: []config.Alias{},
},
{
Name: "flags",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STEPS"},
Type: "[]string",
Mandatory: false,
Aliases: []config.Alias{},
},
{
Name: "logSuccessfulMavenTransfers",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS"},
Type: "bool",
Mandatory: false,
Aliases: []config.Alias{},
},
{
Name: "returnStdout",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS"},
Type: "bool",
Mandatory: false,
Aliases: []config.Alias{},
},
},
},
},
}
return theMetaData
}

View File

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

View File

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

118
pkg/maven/maven.go Normal file
View File

@@ -0,0 +1,118 @@
package maven
import (
"bytes"
"github.com/SAP/jenkins-library/pkg/http"
"github.com/SAP/jenkins-library/pkg/log"
"io"
"strings"
)
type ExecuteOptions struct {
PomPath string `json:"pomPath,omitempty"`
ProjectSettingsFile string `json:"projectSettingsFile,omitempty"`
GlobalSettingsFile string `json:"globalSettingsFile,omitempty"`
M2Path string `json:"m2Path,omitempty"`
Goals []string `json:"goals,omitempty"`
Defines []string `json:"defines,omitempty"`
Flags []string `json:"flags,omitempty"`
LogSuccessfulMavenTransfers bool `json:"logSuccessfulMavenTransfers,omitempty"`
ReturnStdout bool `json:"returnStdout,omitempty"`
}
type mavenExecRunner interface {
Stdout(out io.Writer)
Stderr(err io.Writer)
RunExecutable(e string, p ...string) error
}
const mavenExecutable = "mvn"
func Execute(options *ExecuteOptions, command mavenExecRunner) (string, error) {
stdOutBuf, stdOut := evaluateStdOut(options)
command.Stdout(stdOut)
command.Stderr(log.Entry().Writer())
parameters := getParametersFromOptions(options, &http.Client{})
err := command.RunExecutable(mavenExecutable, parameters...)
if err != nil {
log.Entry().
WithError(err).
WithField("command", append([]string{mavenExecutable}, parameters...)).
Fatal("failed to execute run command")
}
if stdOutBuf == nil {
return "", nil
}
return string(stdOutBuf.Bytes()), nil
}
func evaluateStdOut(config *ExecuteOptions) (*bytes.Buffer, io.Writer) {
var stdOutBuf *bytes.Buffer
var stdOut io.Writer
stdOut = log.Entry().Writer()
if config.ReturnStdout {
stdOutBuf = new(bytes.Buffer)
stdOut = io.MultiWriter(stdOut, stdOutBuf)
}
return stdOutBuf, stdOut
}
func getParametersFromOptions(options *ExecuteOptions, client http.Downloader) []string {
var parameters []string
if options.GlobalSettingsFile != "" {
globalSettingsFileName := options.GlobalSettingsFile
if strings.HasPrefix(options.GlobalSettingsFile, "http:") || strings.HasPrefix(options.GlobalSettingsFile, "https:") {
downloadSettingsFromURL(options.ProjectSettingsFile, "globalSettings.xml", client)
globalSettingsFileName = "globalSettings.xml"
}
parameters = append(parameters, "--global-settings", globalSettingsFileName)
}
if options.ProjectSettingsFile != "" {
projectSettingsFileName := options.ProjectSettingsFile
if strings.HasPrefix(options.ProjectSettingsFile, "http:") || strings.HasPrefix(options.ProjectSettingsFile, "https:") {
downloadSettingsFromURL(options.ProjectSettingsFile, "projectSettings.xml", client)
projectSettingsFileName = "projectSettings.xml"
}
parameters = append(parameters, "--settings", projectSettingsFileName)
}
if options.M2Path != "" {
parameters = append(parameters, "-Dmaven.repo.local="+options.M2Path)
}
if options.PomPath != "" {
parameters = append(parameters, "--file", options.PomPath)
}
if options.Flags != nil {
parameters = append(parameters, options.Flags...)
}
if options.Defines != nil {
parameters = append(parameters, options.Defines...)
}
parameters = append(parameters, "--batch-mode")
if options.LogSuccessfulMavenTransfers {
parameters = append(parameters, "-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn")
}
parameters = append(parameters, options.Goals...)
return parameters
}
// ToDo replace with pkg/maven/settings GetSettingsFile
func downloadSettingsFromURL(url, filename string, client http.Downloader) {
err := client.DownloadFile(url, filename, nil, nil)
if err != nil {
log.Entry().WithError(err).Fatal("Failed to download maven settings from: " + url)
}
}

114
pkg/maven/maven_test.go Normal file
View File

@@ -0,0 +1,114 @@
package maven
import (
"errors"
"github.com/SAP/jenkins-library/pkg/mock"
"net/http"
"testing"
piperHttp "github.com/SAP/jenkins-library/pkg/http"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/stretchr/testify/assert"
)
func TestExecute(t *testing.T) {
t.Run("should return stdOut", func(t *testing.T) {
expectedOutput := "mocked output"
execMockRunner := mock.ExecMockRunner{}
execMockRunner.StdoutReturn = map[string]string{"mvn --file pom.xml --batch-mode": "mocked output"}
opts := ExecuteOptions{PomPath: "pom.xml", ReturnStdout: true}
mavenOutput, _ := Execute(&opts, &execMockRunner)
assert.Equal(t, expectedOutput, mavenOutput)
})
t.Run("should not return stdOut", func(t *testing.T) {
expectedOutput := ""
execMockRunner := mock.ExecMockRunner{}
execMockRunner.StdoutReturn = map[string]string{"mvn --file pom.xml --batch-mode": "mocked output"}
opts := ExecuteOptions{PomPath: "pom.xml", ReturnStdout: false}
mavenOutput, _ := Execute(&opts, &execMockRunner)
assert.Equal(t, expectedOutput, mavenOutput)
})
t.Run("should log that command failed if executing maven failed", func(t *testing.T) {
var hasFailed bool
log.Entry().Logger.ExitFunc = func(int) { hasFailed = true }
execMockRunner := mock.ExecMockRunner{ShouldFailOnCommand: map[string]error{"mvn --file pom.xml --batch-mode": errors.New("error case")}}
opts := ExecuteOptions{PomPath: "pom.xml", ReturnStdout: false}
output, _ := Execute(&opts, &execMockRunner)
assert.True(t, hasFailed, "failed to execute run command")
assert.Equal(t, output, "")
})
t.Run("should have all configured parameters in the exec call", func(t *testing.T) {
execMockRunner := mock.ExecMockRunner{}
opts := ExecuteOptions{PomPath: "pom.xml", ProjectSettingsFile: "settings.xml",
GlobalSettingsFile: "anotherSettings.xml", M2Path: ".m2/",
Goals: []string{"flatten", "install"}, Defines: []string{"-Da=b"},
Flags: []string{"-q"}, LogSuccessfulMavenTransfers: true,
ReturnStdout: false}
expectedParameters := []string{"--global-settings", "anotherSettings.xml", "--settings", "settings.xml",
"-Dmaven.repo.local=.m2/", "--file", "pom.xml", "-q", "-Da=b", "--batch-mode",
"-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn", "flatten", "install"}
mavenOutput, _ := Execute(&opts, &execMockRunner)
assert.Equal(t, len(execMockRunner.Calls[0].Params), len(expectedParameters))
assert.Equal(t, execMockRunner.Calls[0], mock.ExecCall{Exec: "mvn", Params: expectedParameters})
assert.Equal(t, "", mavenOutput)
})
}
type mockDownloader struct {
shouldFail bool
}
func (m *mockDownloader) DownloadFile(url, filename string, header http.Header, cookies []*http.Cookie) error {
if m.shouldFail {
return errors.New("something happened")
}
return nil
}
func (m *mockDownloader) SetOptions(options piperHttp.ClientOptions) {
return
}
func TestGetParameters(t *testing.T) {
t.Run("should resolve configured parameters and download the settings files", func(t *testing.T) {
mockClient := mockDownloader{shouldFail: false}
opts := ExecuteOptions{PomPath: "pom.xml", GlobalSettingsFile: "https://mysettings.com", ProjectSettingsFile: "http://myprojectsettings.com", ReturnStdout: false}
expectedParameters := []string{"--global-settings", "globalSettings.xml", "--settings", "projectSettings.xml", "--file", "pom.xml", "--batch-mode"}
parameters := getParametersFromOptions(&opts, &mockClient)
assert.Equal(t, len(parameters), len(expectedParameters))
assert.Equal(t, parameters, expectedParameters)
})
}
func TestDownloadSettingsFromURL(t *testing.T) {
t.Run("should pass if download is successful", func(t *testing.T) {
var hasFailed bool
log.Entry().Logger.ExitFunc = func(int) { hasFailed = true }
mockClient := mockDownloader{shouldFail: false}
downloadSettingsFromURL("anyURL", "settings.xml", &mockClient)
assert.False(t, hasFailed)
})
t.Run("should fail if download fails", func(t *testing.T) {
var hasFailed bool
log.Entry().Logger.ExitFunc = func(int) { hasFailed = true }
mockClient := mockDownloader{shouldFail: true}
downloadSettingsFromURL("anyURL", "settings.xml", &mockClient)
assert.True(t, hasFailed, "expected command to exit with fatal")
})
}

View File

@@ -0,0 +1,68 @@
metadata:
name: mavenExecute
description: This step allows to run maven commands
longDescription: |
This step runs a maven command based on the parameters provided to the step.
spec:
inputs:
params:
- name: pomPath
type: string
description: Path to the pom file that should be used.
scope:
- PARAMETERS
- STEPS
mandatory: false
- name: projectSettingsFile
type: string
description: Path to the mvn settings file that should be used as project settings file.
scope:
- PARAMETERS
- STEPS
mandatory: false
- name: globalSettingsFile
type: string
description: Path to the mvn settings file that should be used as global settings file.
scope:
- PARAMETERS
- STEPS
mandatory: false
- name: m2Path
type: string
description: Path to the location of the local repository that should be used.
scope:
- PARAMETERS
- STEPS
mandatory: false
- name: goals
type: "[]string"
description: Maven goals that should be executed.
scope:
- PARAMETERS
mandatory: true
- name: defines
type: "[]string"
description: Additional properties in form of -Dkey=value.
scope:
- PARAMETERS
mandatory: false
- name: flags
type: "[]string"
description: Flags to provide when running mvn.
scope:
- PARAMETERS
- STEPS
mandatory: false
- name: logSuccessfulMavenTransfers
type: bool
description: Configures maven to log successful downloads. This is set to `false` by default to reduce the noise in build logs.
scope:
- PARAMETERS
default: false
mandatory: false
- name: returnStdout
type: bool
description: Returns the output of the maven command for further processing.
scope:
- PARAMETERS
default: false