You've already forked sap-jenkins-library
							
							
				mirror of
				https://github.com/SAP/jenkins-library.git
				synced 2025-10-30 23:57:50 +02:00 
			
		
		
		
	GPP Init Stage needs to consider mta yaml path (#3305)
mtaBuild - support config.source to yaml path
This commit is contained in:
		| @@ -196,7 +196,7 @@ func mavenBuildMetadata() config.StepData { | ||||
| 					{ | ||||
| 						Name:        "pomPath", | ||||
| 						ResourceRef: []config.ResourceReference{}, | ||||
| 						Scope:       []string{"PARAMETERS", "STEPS"}, | ||||
| 						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"}, | ||||
| 						Type:        "string", | ||||
| 						Mandatory:   false, | ||||
| 						Aliases:     []config.Alias{}, | ||||
|   | ||||
| @@ -8,6 +8,7 @@ import ( | ||||
| 	"net/http" | ||||
| 	"os" | ||||
| 	"path" | ||||
| 	"path/filepath" | ||||
| 	"strconv" | ||||
| 	"strings" | ||||
| 	"text/template" | ||||
| @@ -160,7 +161,7 @@ func runMtaBuild(config mtaBuildOptions, | ||||
|  | ||||
| 	err = utils.SetNpmRegistries(config.DefaultNpmRegistry) | ||||
|  | ||||
| 	mtaYamlFile := "mta.yaml" | ||||
| 	mtaYamlFile := filepath.Join(getSourcePath(config), "mta.yaml") | ||||
| 	mtaYamlFileExists, err := utils.FileExists(mtaYamlFile) | ||||
|  | ||||
| 	if err != nil { | ||||
| @@ -199,16 +200,9 @@ func runMtaBuild(config mtaBuildOptions, | ||||
| 	if len(config.Extensions) != 0 { | ||||
| 		call = append(call, fmt.Sprintf("--extensions=%s", config.Extensions)) | ||||
| 	} | ||||
| 	if config.Source != "" && config.Source != "./" { | ||||
| 		call = append(call, "--source", config.Source) | ||||
| 	} else { | ||||
| 		call = append(call, "--source", "./") | ||||
| 	} | ||||
| 	if config.Target != "" && config.Target != "./" { | ||||
| 		call = append(call, "--target", config.Target) | ||||
| 	} else { | ||||
| 		call = append(call, "--target", "./") | ||||
| 	} | ||||
|  | ||||
| 	call = append(call, "--source", getSourcePath(config)) | ||||
| 	call = append(call, "--target", getAbsPath(getMtarFileRoot(config))) | ||||
|  | ||||
| 	if config.Jobs > 0 { | ||||
| 		call = append(call, "--mode=verbose") | ||||
| @@ -255,7 +249,8 @@ func runMtaBuild(config mtaBuildOptions, | ||||
| 	} | ||||
| 	commonPipelineEnvironment.custom.buildSettingsInfo = buildSettingsInfo | ||||
|  | ||||
| 	commonPipelineEnvironment.mtarFilePath = mtarName | ||||
| 	commonPipelineEnvironment.mtarFilePath = filepath.ToSlash(getMtarFilePath(config, mtarName)) | ||||
| 	commonPipelineEnvironment.custom.mtaBuildToolDesc = filepath.ToSlash(mtaYamlFile) | ||||
|  | ||||
| 	if config.InstallArtifacts { | ||||
| 		// install maven artifacts in local maven repo because `mbt build` executes `mvn package -B` | ||||
| @@ -500,3 +495,49 @@ func getMtaID(mtaYamlFile string, utils mtaBuildUtils) (string, error) { | ||||
|  | ||||
| 	return id, nil | ||||
| } | ||||
|  | ||||
| // the "source" path locates the project's root | ||||
| func getSourcePath(config mtaBuildOptions) string { | ||||
| 	path := config.Source | ||||
| 	if path == "" { | ||||
| 		path = "./" | ||||
| 	} | ||||
| 	return filepath.FromSlash(path) | ||||
| } | ||||
|  | ||||
| // target defines a subfolder of the project's root | ||||
| func getTargetPath(config mtaBuildOptions) string { | ||||
| 	path := config.Target | ||||
| 	if path == "" { | ||||
| 		path = "./" | ||||
| 	} | ||||
| 	return filepath.FromSlash(path) | ||||
| } | ||||
|  | ||||
| // the "mtar" path resides below the project's root | ||||
| // path=<config.source>/<config.target>/<mtarname> | ||||
| func getMtarFileRoot(config mtaBuildOptions) string { | ||||
| 	sourcePath := getSourcePath(config) | ||||
| 	targetPath := getTargetPath(config) | ||||
|  | ||||
| 	return filepath.FromSlash(filepath.Join(sourcePath, targetPath)) | ||||
| } | ||||
|  | ||||
| func getMtarFilePath(config mtaBuildOptions, mtarName string) string { | ||||
| 	root := getMtarFileRoot(config) | ||||
|  | ||||
| 	if root == "" || root == filepath.FromSlash("./") { | ||||
| 		return mtarName | ||||
| 	} | ||||
|  | ||||
| 	return filepath.FromSlash(filepath.Join(root, mtarName)) | ||||
| } | ||||
|  | ||||
| func getAbsPath(path string) string { | ||||
| 	abspath, err := filepath.Abs(path) | ||||
| 	// ignore error, pass customers path value in case of trouble | ||||
| 	if err != nil { | ||||
| 		abspath = path | ||||
| 	} | ||||
| 	return filepath.FromSlash(abspath) | ||||
| } | ||||
|   | ||||
| @@ -43,6 +43,7 @@ type mtaBuildOptions struct { | ||||
| type mtaBuildCommonPipelineEnvironment struct { | ||||
| 	mtarFilePath string | ||||
| 	custom       struct { | ||||
| 		mtaBuildToolDesc  string | ||||
| 		mtarPublishedURL  string | ||||
| 		buildSettingsInfo string | ||||
| 	} | ||||
| @@ -55,6 +56,7 @@ func (p *mtaBuildCommonPipelineEnvironment) persist(path, resourceName string) { | ||||
| 		value    interface{} | ||||
| 	}{ | ||||
| 		{category: "", name: "mtarFilePath", value: p.mtarFilePath}, | ||||
| 		{category: "custom", name: "mtaBuildToolDesc", value: p.custom.mtaBuildToolDesc}, | ||||
| 		{category: "custom", name: "mtarPublishedUrl", value: p.custom.mtarPublishedURL}, | ||||
| 		{category: "custom", name: "buildSettingsInfo", value: p.custom.buildSettingsInfo}, | ||||
| 	} | ||||
| @@ -426,6 +428,7 @@ func mtaBuildMetadata() config.StepData { | ||||
| 						Type: "piperEnvironment", | ||||
| 						Parameters: []map[string]interface{}{ | ||||
| 							{"Name": "mtarFilePath"}, | ||||
| 							{"Name": "custom/mtaBuildToolDesc"}, | ||||
| 							{"Name": "custom/mtarPublishedUrl"}, | ||||
| 							{"Name": "custom/buildSettingsInfo"}, | ||||
| 						}, | ||||
|   | ||||
| @@ -3,6 +3,7 @@ package cmd | ||||
| import ( | ||||
| 	"errors" | ||||
| 	"net/http" | ||||
| 	"os" | ||||
| 	"path/filepath" | ||||
| 	"testing" | ||||
|  | ||||
| @@ -46,7 +47,7 @@ func newMtaBuildTestUtilsBundle() *mtaBuildTestUtilsBundle { | ||||
| 	return &utilsBundle | ||||
| } | ||||
|  | ||||
| func TestMarBuild(t *testing.T) { | ||||
| func TestMtaBuild(t *testing.T) { | ||||
|  | ||||
| 	cpe := mtaBuildCommonPipelineEnvironment{} | ||||
|  | ||||
| @@ -171,7 +172,7 @@ func TestMarBuild(t *testing.T) { | ||||
|  | ||||
| 		if assert.Len(t, utilsMock.Calls, 1) { | ||||
| 			assert.Equal(t, "mbt", utilsMock.Calls[0].Exec) | ||||
| 			assert.Equal(t, []string{"build", "--mtar", "myName.mtar", "--platform", "CF", "--source", "./", "--target", "./"}, utilsMock.Calls[0].Params) | ||||
| 			assert.Equal(t, []string{"build", "--mtar", "myName.mtar", "--platform", "CF", "--source", filepath.FromSlash("./"), "--target", filepath.FromSlash(_ignoreError(os.Getwd()))}, utilsMock.Calls[0].Params) | ||||
| 		} | ||||
| 		assert.Equal(t, "myName.mtar", cpe.mtarFilePath) | ||||
| 	}) | ||||
| @@ -193,9 +194,13 @@ func TestMarBuild(t *testing.T) { | ||||
|  | ||||
| 			if assert.Len(t, utilsMock.Calls, 1) { | ||||
| 				assert.Equal(t, "mbt", utilsMock.Calls[0].Exec) | ||||
| 				assert.Equal(t, []string{"build", "--mtar", "myName.mtar", "--platform", "CF", "--source", "mySourcePath/", "--target", "myTargetPath/"}, utilsMock.Calls[0].Params) | ||||
| 				assert.Equal(t, []string{"build", "--mtar", "myName.mtar", "--platform", "CF", | ||||
| 					"--source", filepath.FromSlash("mySourcePath/"), | ||||
| 					"--target", filepath.Join(_ignoreError(os.Getwd()), filepath.FromSlash("mySourcePath/myTargetPath/"))}, | ||||
| 					utilsMock.Calls[0].Params) | ||||
| 			} | ||||
| 			assert.Equal(t, "myName.mtar", cpe.mtarFilePath) | ||||
| 			assert.Equal(t, "mySourcePath/myTargetPath/myName.mtar", cpe.mtarFilePath) | ||||
| 			assert.Equal(t, "mySourcePath/mta.yaml", cpe.custom.mtaBuildToolDesc) | ||||
| 		}) | ||||
| 	}) | ||||
|  | ||||
| @@ -278,3 +283,121 @@ func TestMarBuild(t *testing.T) { | ||||
| 		}) | ||||
| 	}) | ||||
| } | ||||
|  | ||||
| func TestMtaBuildSourceDir(t *testing.T) { | ||||
|  | ||||
| 	t.Run("getSourcePath", func(t *testing.T) { | ||||
| 		t.Parallel() | ||||
|  | ||||
| 		t.Run("getPath dir unset", func(t *testing.T) { | ||||
| 			options := mtaBuildOptions{Source: "", Target: ""} | ||||
| 			assert.Equal(t, filepath.FromSlash("./"), getSourcePath(options)) | ||||
| 			assert.Equal(t, filepath.FromSlash("./"), getTargetPath(options)) | ||||
| 		}) | ||||
| 		t.Run("getPath source set", func(t *testing.T) { | ||||
| 			options := mtaBuildOptions{Source: "spath", Target: ""} | ||||
| 			assert.Equal(t, filepath.FromSlash("spath"), getSourcePath(options)) | ||||
| 			assert.Equal(t, filepath.FromSlash("./"), getTargetPath(options)) | ||||
| 		}) | ||||
| 		t.Run("getPath target set", func(t *testing.T) { | ||||
| 			options := mtaBuildOptions{Source: "", Target: "tpath"} | ||||
| 			assert.Equal(t, filepath.FromSlash("./"), getSourcePath(options)) | ||||
| 			assert.Equal(t, filepath.FromSlash("tpath"), getTargetPath(options)) | ||||
| 		}) | ||||
| 		t.Run("getPath dir set to relative path", func(t *testing.T) { | ||||
| 			options := mtaBuildOptions{Source: "spath", Target: "tpath"} | ||||
| 			assert.Equal(t, filepath.FromSlash("spath"), getSourcePath(options)) | ||||
| 			assert.Equal(t, filepath.FromSlash("tpath"), getTargetPath(options)) | ||||
| 		}) | ||||
| 		t.Run("getPath dir ends with seperator", func(t *testing.T) { | ||||
| 			options := mtaBuildOptions{Source: "spath/", Target: "tpath/"} | ||||
| 			assert.Equal(t, filepath.FromSlash("spath/"), getSourcePath(options)) | ||||
| 			assert.Equal(t, filepath.FromSlash("tpath/"), getTargetPath(options)) | ||||
| 		}) | ||||
| 		t.Run("getPath dir set to absolute path", func(t *testing.T) { | ||||
| 			sourcePath := filepath.Join(_ignoreError(os.Getwd()), "spath") | ||||
| 			targetPath := filepath.Join(_ignoreError(os.Getwd()), "tpath") | ||||
| 			options := mtaBuildOptions{Source: sourcePath, Target: targetPath} | ||||
| 			assert.Equal(t, filepath.FromSlash(sourcePath), getSourcePath(options)) | ||||
| 			assert.Equal(t, filepath.FromSlash(targetPath), getTargetPath(options)) | ||||
| 		}) | ||||
| 	}) | ||||
|  | ||||
| 	t.Run("find build tool descriptor from configuration", func(t *testing.T) { | ||||
| 		t.Parallel() | ||||
| 		cpe := mtaBuildCommonPipelineEnvironment{} | ||||
| 		t.Run("default mta.yaml", func(t *testing.T) { | ||||
| 			utilsMock := newMtaBuildTestUtilsBundle() | ||||
|  | ||||
| 			utilsMock.AddFile("mta.yaml", []byte("already there")) | ||||
|  | ||||
| 			_ = runMtaBuild(mtaBuildOptions{ApplicationName: "myApp"}, &cpe, utilsMock) | ||||
|  | ||||
| 			assert.False(t, utilsMock.HasWrittenFile("mta.yaml")) | ||||
| 		}) | ||||
| 		t.Run("create mta.yaml from config.source", func(t *testing.T) { | ||||
| 			utilsMock := newMtaBuildTestUtilsBundle() | ||||
|  | ||||
| 			utilsMock.AddFile("package.json", []byte("{\"name\": \"myName\", \"version\": \"1.2.3\"}")) | ||||
|  | ||||
| 			_ = runMtaBuild(mtaBuildOptions{ApplicationName: "myApp", Source: "create"}, &cpe, utilsMock) | ||||
|  | ||||
| 			assert.True(t, utilsMock.HasWrittenFile("create/mta.yaml")) | ||||
| 		}) | ||||
| 		t.Run("read yaml from config.source", func(t *testing.T) { | ||||
| 			utilsMock := newMtaBuildTestUtilsBundle() | ||||
|  | ||||
| 			utilsMock.AddFile("path/mta.yaml", []byte("already there")) | ||||
|  | ||||
| 			_ = runMtaBuild(mtaBuildOptions{ApplicationName: "myApp", Source: "path"}, &cpe, utilsMock) | ||||
|  | ||||
| 			assert.False(t, utilsMock.HasWrittenFile("path/mta.yaml")) | ||||
| 		}) | ||||
| 	}) | ||||
|  | ||||
| } | ||||
|  | ||||
| func TestMtaBuildMtar(t *testing.T) { | ||||
|  | ||||
| 	t.Run("getMtarName", func(t *testing.T) { | ||||
| 		t.Parallel() | ||||
|  | ||||
| 		t.Run("mtar name from yaml", func(t *testing.T) { | ||||
| 			utilsMock := newMtaBuildTestUtilsBundle() | ||||
| 			utilsMock.AddFile("mta.yaml", []byte("ID: \"nameFromMtar\"")) | ||||
|  | ||||
| 			assert.Equal(t, filepath.FromSlash("nameFromMtar.mtar"), _ignoreError(getMtarName(mtaBuildOptions{MtarName: ""}, "mta.yaml", utilsMock))) | ||||
| 		}) | ||||
| 		t.Run("mtar name from config", func(t *testing.T) { | ||||
| 			utilsMock := newMtaBuildTestUtilsBundle() | ||||
| 			utilsMock.AddFile("mta.yaml", []byte("ID: \"nameFromMtar\"")) | ||||
|  | ||||
| 			assert.Equal(t, filepath.FromSlash("nameFromConfig.mtar"), _ignoreError(getMtarName(mtaBuildOptions{MtarName: "nameFromConfig.mtar"}, "mta.yaml", utilsMock))) | ||||
| 		}) | ||||
| 	}) | ||||
|  | ||||
| 	t.Run("getMtarFilePath", func(t *testing.T) { | ||||
| 		t.Parallel() | ||||
|  | ||||
| 		t.Run("plain mtar name", func(t *testing.T) { | ||||
| 			assert.Equal(t, "mta.mtar", getMtarFilePath(mtaBuildOptions{Source: "", Target: ""}, "mta.mtar")) | ||||
| 		}) | ||||
| 		t.Run("plain mtar name from default", func(t *testing.T) { | ||||
| 			assert.Equal(t, "mta.mtar", getMtarFilePath(mtaBuildOptions{Source: "./", Target: "./"}, "mta.mtar")) | ||||
| 		}) | ||||
| 		t.Run("source path", func(t *testing.T) { | ||||
| 			assert.Equal(t, filepath.FromSlash("source/mta.mtar"), getMtarFilePath(mtaBuildOptions{Source: "source", Target: ""}, "mta.mtar")) | ||||
| 		}) | ||||
| 		t.Run("target path", func(t *testing.T) { | ||||
| 			assert.Equal(t, filepath.FromSlash("target/mta.mtar"), getMtarFilePath(mtaBuildOptions{Source: "", Target: "target"}, "mta.mtar")) | ||||
| 		}) | ||||
| 		t.Run("source and target path", func(t *testing.T) { | ||||
| 			assert.Equal(t, filepath.FromSlash("source/target/mta.mtar"), getMtarFilePath(mtaBuildOptions{Source: "source", Target: "target"}, "mta.mtar")) | ||||
| 		}) | ||||
| 	}) | ||||
|  | ||||
| } | ||||
|  | ||||
| func _ignoreError(s string, e error) string { | ||||
| 	return s | ||||
| } | ||||
|   | ||||
| @@ -59,7 +59,7 @@ func TestNPMProject(t *testing.T) { | ||||
| 		t.Fatalf("Piper command failed %s", err) | ||||
| 	} | ||||
|  | ||||
| 	container.assertHasOutput(t, "INFO the MTA archive generated at: test-mta-js.mtar") | ||||
| 	container.assertHasOutput(t, "INFO the MTA archive generated at: /project/test-mta-js.mtar") | ||||
| } | ||||
|  | ||||
| func TestNPMProjectInstallsDevDependencies(t *testing.T) { | ||||
|   | ||||
| @@ -20,6 +20,7 @@ spec: | ||||
|         description: Path to the pom file which should be installed including all children. | ||||
|         scope: | ||||
|           - PARAMETERS | ||||
|           - STAGES | ||||
|           - STEPS | ||||
|         mandatory: false | ||||
|         default: pom.xml | ||||
|   | ||||
| @@ -224,6 +224,7 @@ spec: | ||||
|         type: piperEnvironment | ||||
|         params: | ||||
|           - name: mtarFilePath | ||||
|           - name: custom/mtaBuildToolDesc | ||||
|           - name: custom/mtarPublishedUrl | ||||
|           - name: custom/buildSettingsInfo | ||||
|   containers: | ||||
|   | ||||
| @@ -226,6 +226,34 @@ public class TmsUploadTest extends BasePiperTest { | ||||
|         assertThat(calledTmsMethodsWithArgs[3], is("updateMtaExtDescriptor('${uri}', 'myToken', 1, 2, './dummy2.mtaext', '1.2.2', 'Git CommitId: testCommitId', 'Test User')")) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     public void testMtaBuildDescriptorFromCPE() { | ||||
|         Map nodeExtDescriptorMap = ["testNode1": "dummy.mtaext"] | ||||
|  | ||||
|         jenkinsUtilsStub = new JenkinsUtilsMock("Test User") | ||||
|         binding.workspace = "." | ||||
|         envRule.env.gitCommitId = "testCommitId" | ||||
|  | ||||
|         nullScript.commonPipelineEnvironment.setValue("mtaBuildToolDesc","path/mta.yaml") | ||||
|         readYamlRule.registerYaml('path/mta.yaml','ID: "com.sap.piper.tms.test"' + "\n" + 'version: "9.9.9"') | ||||
|         fileExistsRules.existingFiles.add('path/mta.yaml') | ||||
|  | ||||
|  | ||||
|         stepRule.step.tmsUpload( | ||||
|             script: nullScript, | ||||
|             juStabUtils: utils, | ||||
|             jenkinsUtilsStub: jenkinsUtilsStub, | ||||
|             transportManagementService: tmsStub, | ||||
|             mtaPath: 'dummy.mtar', | ||||
|             nodeName: 'myNode', | ||||
|             credentialsId: 'TMS_ServiceKey', | ||||
|             nodeExtDescriptorMapping: nodeExtDescriptorMap, | ||||
|             mtaVersion: '9.9.9', | ||||
|         ) | ||||
|  | ||||
|         assertThat(calledTmsMethodsWithArgs[2], is("getMtaExtDescriptor('${uri}', 'myToken', 1, 'com.sap.piper.tms.test', '9.9.9')")) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     public void failOnMissingMtaFile() { | ||||
|  | ||||
|   | ||||
| @@ -14,6 +14,7 @@ import static org.hamcrest.Matchers.hasKey | ||||
| import static org.hamcrest.Matchers.is | ||||
| import static org.hamcrest.Matchers.isEmptyOrNullString | ||||
| import static org.hamcrest.Matchers.not | ||||
| import static org.junit.Assert.assertEquals | ||||
| import static org.junit.Assert.assertThat | ||||
| import static org.junit.Assert.assertTrue | ||||
|  | ||||
| @@ -21,12 +22,14 @@ class PiperPipelineStageInitTest extends BasePiperTest { | ||||
|     private JenkinsStepRule jsr = new JenkinsStepRule(this) | ||||
|     private JenkinsLoggingRule jlr = new JenkinsLoggingRule(this) | ||||
|     private JenkinsReadYamlRule jryr = new JenkinsReadYamlRule(this) | ||||
|     private JenkinsReadMavenPomRule jrmpr = new JenkinsReadMavenPomRule(this, null) | ||||
|     private ExpectedException thrown = new ExpectedException() | ||||
|  | ||||
|     @Rule | ||||
|     public RuleChain rules = Rules | ||||
|         .getCommonRules(this) | ||||
|         .around(jryr) | ||||
|         .around(jrmpr) | ||||
|         .around(thrown) | ||||
|         .around(jlr) | ||||
|         .around(jsr) | ||||
| @@ -44,8 +47,15 @@ class PiperPipelineStageInitTest extends BasePiperTest { | ||||
|  | ||||
|         helper.registerAllowedMethod("findFiles", [Map.class], { map -> | ||||
|             switch (map.glob) { | ||||
|                 case 'mta.yaml': | ||||
|                 case 'path/mta.yaml': | ||||
|                 case 'pathFromStep/mta.yaml': | ||||
|                 case 'pathFromStage/mta.yaml': | ||||
|                 case 'pom.xml': | ||||
|                     return [new File('pom.xml')].toArray() | ||||
|                 case 'path/pom.xml': | ||||
|                 case 'pathFromStep/pom.xml': | ||||
|                 case 'pathFromStage/pom.xml': | ||||
|                     return [new File(map.glob)].toArray() | ||||
|                 default: | ||||
|                     return [].toArray() | ||||
|             } | ||||
| @@ -104,7 +114,7 @@ class PiperPipelineStageInitTest extends BasePiperTest { | ||||
|     @Test | ||||
|     void testInitBuildToolDoesNotMatchProject() { | ||||
|  | ||||
|         thrown.expectMessage('[piperPipelineStageInit] buildTool configuration \'npm\' does not fit to your project, please set buildTool as general setting in your .pipeline/config.yml correctly, see also https://sap.github.io/jenkins-library/configuration/') | ||||
|         thrown.expectMessage('[piperPipelineStageInit] buildTool configuration \'npm\' does not fit to your project (buildDescriptorPattern: \'package.json\'), please set buildTool as general setting in your .pipeline/config.yml correctly, see also https://sap.github.io/jenkins-library/configuration/') | ||||
|         jsr.step.piperPipelineStageInit( | ||||
|             script: nullScript, | ||||
|             juStabUtils: utils, | ||||
| @@ -201,6 +211,80 @@ class PiperPipelineStageInitTest extends BasePiperTest { | ||||
|         )) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferBuildToolDescMta() { | ||||
|         assertEquals('mta.yaml', jsr.step.piperPipelineStageInit.inferBuildToolDesc(nullScript, "mta")) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferBuildToolDescMaven() { | ||||
|         assertEquals('pom.xml', jsr.step.piperPipelineStageInit.inferBuildToolDesc(nullScript, "maven")) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferBuildToolDescNpm() { | ||||
|         assertEquals('package.json', jsr.step.piperPipelineStageInit.inferBuildToolDesc(nullScript, "npm")) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferBuildToolDescMtaSource() { | ||||
|         nullScript.commonPipelineEnvironment.configuration = [general: [buildTool: 'mta'], steps : [mtaBuild: [source: 'pathFromStep']]] | ||||
|  | ||||
|         helper.registerAllowedMethod('artifactPrepareVersion', [Map.class, Closure.class], { m, body -> | ||||
|             assertThat(m.filePath, is('pathFromStep/mta.yaml')) | ||||
|             return body() | ||||
|         }) | ||||
|  | ||||
|         jsr.step.piperPipelineStageInit(script: nullScript, juStabUtils: utils) | ||||
|  | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferBuildToolDescMtaSourceStage() { | ||||
|         nullScript.commonPipelineEnvironment.configuration = [general: [buildTool: 'mta'], stages: [Build: [source: 'pathFromStage']], steps : [mtaBuild: [source: 'pathFromStep']]] | ||||
|  | ||||
|         helper.registerAllowedMethod('artifactPrepareVersion', [Map.class, Closure.class], { m, body -> | ||||
|             assertThat(m.filePath, is('pathFromStage/mta.yaml')) | ||||
|             return body() | ||||
|         }) | ||||
|  | ||||
|         jsr.step.piperPipelineStageInit(script: nullScript, juStabUtils: utils) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferBuildToolDescMavenSource() { | ||||
|         nullScript.commonPipelineEnvironment.configuration = [general: [buildTool: 'maven'], steps : [mavenBuild: [pomPath: 'pathFromStep/pom.xml']]] | ||||
|  | ||||
|         helper.registerAllowedMethod('artifactPrepareVersion', [Map.class, Closure.class], { m, body -> | ||||
|             assertThat(m.filePath, is('pathFromStep/pom.xml')) | ||||
|             return body() | ||||
|         }) | ||||
|  | ||||
|         jsr.step.piperPipelineStageInit(script: nullScript, juStabUtils: utils) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferBuildToolDescMavenSourceStage() { | ||||
|         nullScript.commonPipelineEnvironment.configuration = [general: [buildTool: 'maven'], stages: [Build: [pomPath: 'pathFromStage/pom.xml']], steps : [mavenBuild: [pomPath: 'pathFromStep/pom.xml']]] | ||||
|  | ||||
|         helper.registerAllowedMethod('artifactPrepareVersion', [Map.class, Closure.class], { m, body -> | ||||
|             assertThat(m.filePath, is('pathFromStage/pom.xml')) | ||||
|             return body() | ||||
|         }) | ||||
|  | ||||
|         jsr.step.piperPipelineStageInit(script: nullScript, juStabUtils: utils) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferBuildToolDescUnknown() { | ||||
|         assertEquals(null, jsr.step.piperPipelineStageInit.inferBuildToolDesc(nullScript, "unknown")) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferBuildToolDescNull() { | ||||
|         assertEquals(null, jsr.step.piperPipelineStageInit.inferBuildToolDesc(nullScript, null)) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInitInferBuildTool() { | ||||
|         nullScript.commonPipelineEnvironment.configuration = [general: [inferBuildTool: true]] | ||||
| @@ -217,6 +301,33 @@ class PiperPipelineStageInitTest extends BasePiperTest { | ||||
|         )) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferProjectNameFromMta() { | ||||
|         jryr.registerYaml('mta.yaml','ID: "fromMtaYaml"') | ||||
|         assertEquals('fromMtaYaml', jsr.step.piperPipelineStageInit.inferProjectName(nullScript, "mta", "mta.yaml")) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferProjectNameFromMtaSource() { | ||||
|         nullScript.commonPipelineEnvironment.configuration = [general: [buildTool: 'mta', inferProjectName: true], steps : [mtaBuild: [source: 'path']]] | ||||
|  | ||||
|         jryr.registerYaml('path/mta.yaml','ID: "fromPathMtaYaml"') | ||||
|         jsr.step.piperPipelineStageInit(script: nullScript, juStabUtils: utils) | ||||
|         assertEquals('fromPathMtaYaml', nullScript.commonPipelineEnvironment.projectName) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInferProjectNameFromMavenPath() { | ||||
|         jrmpr.registerPom('path/pom.xml', | ||||
|             '<project>' | ||||
|                 + '<groupId>gidFromPathPom</groupId>' | ||||
|                 + '<artifactId>aidFromPathPom</artifactId>' | ||||
|             + '</project>' | ||||
|         ) | ||||
|  | ||||
|         assertEquals('gidFromPathPom-aidFromPathPom', jsr.step.piperPipelineStageInit.inferProjectName(nullScript, "maven", "path/pom.xml")) | ||||
|     } | ||||
|  | ||||
|     @Test | ||||
|     void testInitWithTechnicalStageNames() { | ||||
|         helper.registerAllowedMethod('piperStageWrapper', [Map.class, Closure.class], { m, body -> | ||||
|   | ||||
| @@ -4,18 +4,26 @@ import com.lesfurets.jenkins.unit.BasePipelineTest | ||||
| import org.junit.rules.TestRule | ||||
| import org.junit.runner.Description | ||||
| import org.junit.runners.model.Statement | ||||
| import java.nio.file.Path | ||||
| import java.nio.file.Paths | ||||
|  | ||||
| class JenkinsReadMavenPomRule implements TestRule { | ||||
|  | ||||
|     final BasePipelineTest testInstance | ||||
|     final String testRoot | ||||
|     def poms = [:] | ||||
|  | ||||
|     JenkinsReadMavenPomRule(BasePipelineTest testInstance, String testRoot) { | ||||
|         this.testInstance = testInstance | ||||
|         this.testRoot = testRoot | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     JenkinsReadMavenPomRule registerPom(fileName, pom) { | ||||
|         poms.put(fileName, pom) | ||||
|         return this | ||||
|     } | ||||
|  | ||||
|         @Override | ||||
|     Statement apply(Statement base, Description description) { | ||||
|         return statement(base) | ||||
|     } | ||||
| @@ -25,7 +33,19 @@ class JenkinsReadMavenPomRule implements TestRule { | ||||
|             @Override | ||||
|             void evaluate() throws Throwable { | ||||
|  | ||||
|                 testInstance.helper.registerAllowedMethod('readMavenPom', [Map.class], {m -> return loadPom("${testRoot}/${m.file}")}) | ||||
|                 testInstance.helper.registerAllowedMethod('readMavenPom', [Map.class], { Map m -> | ||||
|                     if(m.text) { | ||||
|                         return loadPomfromText(m.text) | ||||
|                     } else if(m.file) { | ||||
|                         def pom = poms.get(m.file) | ||||
|                         if(pom == null) | ||||
|                             return loadPom("${testRoot}/${m.file}") | ||||
|                         if(pom instanceof Closure) pom = pom() | ||||
|                             return loadPomfromText(pom) | ||||
|                     } else { | ||||
|                         throw new IllegalArgumentException("Key 'text' and 'file' are both missing in map ${m}.") | ||||
|                     } | ||||
|                 }) | ||||
|  | ||||
|                 base.evaluate() | ||||
|             } | ||||
| @@ -33,12 +53,16 @@ class JenkinsReadMavenPomRule implements TestRule { | ||||
|     } | ||||
|  | ||||
|     MockPom loadPom( String path ){ | ||||
|         return new MockPom( path ) | ||||
|         return new MockPom(Paths.get(path)) | ||||
|     } | ||||
|  | ||||
|     MockPom loadPomfromText( String text){ | ||||
|         return new MockPom( text ) | ||||
|     } | ||||
|  | ||||
|     class MockPom { | ||||
|         def pom | ||||
|         MockPom(String path){ | ||||
|         MockPom(Path path){ | ||||
|             def f = new File( path ) | ||||
|             if ( f.exists() ){ | ||||
|                 this.pom = new XmlSlurper().parse(f) | ||||
| @@ -47,6 +71,9 @@ class JenkinsReadMavenPomRule implements TestRule { | ||||
|                 throw new FileNotFoundException( 'Failed to find file: ' + path ) | ||||
|             } | ||||
|         } | ||||
|         MockPom(String text ){ | ||||
|             this.pom = new XmlSlurper().parseText(text) | ||||
|         } | ||||
|         String getVersion(){ | ||||
|             return pom.version | ||||
|         } | ||||
|   | ||||
| @@ -171,12 +171,15 @@ void call(Map parameters = [:]) { | ||||
|             checkForLegacyConfiguration(script: script, legacyConfigSettings: legacyConfigSettings) | ||||
|         } | ||||
|  | ||||
|         String buildTool = checkBuildTool(config) | ||||
|         String buildTool = config.buildTool | ||||
|         String buildToolDesc = inferBuildToolDesc(script, config.buildTool) | ||||
|  | ||||
|         checkBuildTool(buildTool, buildToolDesc) | ||||
|  | ||||
|         script.commonPipelineEnvironment.projectName = config.projectName | ||||
|  | ||||
|         if (!script.commonPipelineEnvironment.projectName && config.inferProjectName) { | ||||
|             script.commonPipelineEnvironment.projectName = inferProjectName(script, buildTool) | ||||
|             script.commonPipelineEnvironment.projectName = inferProjectName(script, buildTool, buildToolDesc) | ||||
|         } | ||||
|  | ||||
|         if (Boolean.valueOf(env.ON_K8S) && config.containerMapResource) { | ||||
| @@ -221,6 +224,9 @@ void call(Map parameters = [:]) { | ||||
|             if (config.inferBuildTool) { | ||||
|                 prepareVersionParams.buildTool = buildTool | ||||
|             } | ||||
|             if(buildToolDesc) { | ||||
|                 prepareVersionParams.filePath = buildToolDesc | ||||
|             } | ||||
|             if (env.ON_K8S && !config.runArtifactVersioningOnPod) { | ||||
|                 // We force dockerImage: "" for the K8S case to avoid the execution of artifactPrepareVersion in a K8S Pod. | ||||
|                 // Since artifactPrepareVersion may need the ".git" folder in order to push a tag, it would need to be part of the stashing. | ||||
| @@ -235,41 +241,50 @@ void call(Map parameters = [:]) { | ||||
|     } | ||||
| } | ||||
|  | ||||
| private String inferProjectName(Script script, String buildTool) { | ||||
| // Infer build tool descriptor (maven, npm, mta) | ||||
| private static String inferBuildToolDesc(script, buildTool) { | ||||
|  | ||||
|     String buildToolDesc = null | ||||
|  | ||||
|     switch (buildTool) { | ||||
|         case 'maven': | ||||
|             def pom = script.readMavenPom file: 'pom.xml' | ||||
|             Map configBuild = script.commonPipelineEnvironment.getStepConfiguration('mavenBuild', 'Build') | ||||
|             buildToolDesc = configBuild.pomPath? configBuild.pomPath : 'pom.xml' | ||||
|             break | ||||
|         case 'npm': // no parameter for the descriptor path | ||||
|             buildToolDesc = 'package.json' | ||||
|             break | ||||
|         case 'mta': | ||||
|             Map configBuild = script.commonPipelineEnvironment.getStepConfiguration('mtaBuild', 'Build') | ||||
|             buildToolDesc = configBuild.source? configBuild.source + '/mta.yaml' : 'mta.yaml' | ||||
|             break | ||||
|         default: | ||||
|             break; | ||||
|     } | ||||
|  | ||||
|     return buildToolDesc | ||||
| } | ||||
|  | ||||
| private String inferProjectName(Script script, String buildTool, String buildToolDesc) { | ||||
|     switch (buildTool) { | ||||
|         case 'maven': | ||||
|             def pom = script.readMavenPom file: buildToolDesc | ||||
|             return "${pom.groupId}-${pom.artifactId}" | ||||
|         case 'npm': | ||||
|             Map packageJson = script.readJSON file: 'package.json' | ||||
|             Map packageJson = script.readJSON file: buildToolDesc | ||||
|             return packageJson.name | ||||
|         case 'mta': | ||||
|             Map mta = script.readYaml file: 'mta.yaml' | ||||
|             Map mta = script.readYaml file: buildToolDesc | ||||
|             return mta.ID | ||||
|     } | ||||
|  | ||||
|     script.error "Cannot infer projectName. Project buildTool was none of the expected ones 'mta', 'maven', or 'npm'." | ||||
| } | ||||
|  | ||||
| private String checkBuildTool(config) { | ||||
|     def buildDescriptorPattern = '' | ||||
|     String buildTool = config.buildTool | ||||
|  | ||||
|     switch (buildTool) { | ||||
|         case 'maven': | ||||
|             buildDescriptorPattern = 'pom.xml' | ||||
|             break | ||||
|         case 'npm': | ||||
|             buildDescriptorPattern = 'package.json' | ||||
|             break | ||||
|         case 'mta': | ||||
|             buildDescriptorPattern = 'mta.yaml' | ||||
|             break | ||||
|     } | ||||
| private checkBuildTool(String buildTool, String buildDescriptorPattern) { | ||||
|     if (buildDescriptorPattern && !findFiles(glob: buildDescriptorPattern)) { | ||||
|         error "[${STEP_NAME}] buildTool configuration '${config.buildTool}' does not fit to your project, please set buildTool as general setting in your .pipeline/config.yml correctly, see also https://sap.github.io/jenkins-library/configuration/" | ||||
|         error "[${STEP_NAME}] buildTool configuration '${buildTool}' does not fit to your project (buildDescriptorPattern: '${buildDescriptorPattern}'), please set buildTool as general setting in your .pipeline/config.yml correctly, see also https://sap.github.io/jenkins-library/configuration/" | ||||
|     } | ||||
|     return buildTool | ||||
| } | ||||
|  | ||||
| private void initStashConfiguration (script, stashSettings, customStashSettings, verbose) { | ||||
|   | ||||
| @@ -146,7 +146,7 @@ void call(Map parameters = [:]) { | ||||
|                 // so that user can get them in one pipeline run | ||||
|                 // put the validation here, because we need uri and token to call tms get nodes api | ||||
|                 List nodes = tms.getNodes(uri, token).getAt("nodes"); | ||||
|                 Map mtaYaml = getMtaYaml(); | ||||
|                 Map mtaYaml = getMtaYaml(script.commonPipelineEnvironment.getValue('mtaBuildToolDesc')); | ||||
|                 Map nodeIdExtDesMap = validateNodeExtDescriptorMapping(nodeExtDescriptorMapping, nodes, mtaYaml, mtaVersion) | ||||
|  | ||||
|                 if(nodeIdExtDesMap) { | ||||
| @@ -181,22 +181,23 @@ def String getMtaId(String extDescriptorFilePath){ | ||||
|     return mtaId | ||||
| } | ||||
|  | ||||
| def Map getMtaYaml() { | ||||
|     if(fileExists("mta.yaml")) { | ||||
|         def mtaYaml = readYaml file: "mta.yaml" | ||||
| def Map getMtaYaml(String mtaBuildToolDesc) { | ||||
|     mtaBuildToolDesc = mtaBuildToolDesc?:"mta.yaml" | ||||
|     if(fileExists(mtaBuildToolDesc)) { | ||||
|         def mtaYaml = readYaml file: mtaBuildToolDesc | ||||
|         if (!mtaYaml.ID || !mtaYaml.version) { | ||||
|             def errorMsg | ||||
|             if (!mtaYaml.ID) { | ||||
|                 errorMsg = "Property 'ID' is not found in mta.yaml." | ||||
|                 errorMsg = "Property 'ID' is not found in ${mtaBuildToolDesc}." | ||||
|             } | ||||
|             if (!mtaYaml.version) { | ||||
|                 errorMsg += "Property 'version' is not found in mta.yaml." | ||||
|                 errorMsg += "Property 'version' is not found in ${mtaBuildToolDesc}." | ||||
|             } | ||||
|             error errorMsg | ||||
|         } | ||||
|         return mtaYaml | ||||
|     } else { | ||||
|         error "mta.yaml is not found in the root folder of the project." | ||||
|         error "${mtaBuildToolDesc} is not found in the root folder of the project." | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
		Reference in New Issue
	
	Block a user