diff --git a/artifacts/metaexport.groovy b/artifacts/metaexport.groovy index b4d4a6d..0ca5da7 100644 --- a/artifacts/metaexport.groovy +++ b/artifacts/metaexport.groovy @@ -4,7 +4,6 @@ def combineSubjobArtifacts(meta, subJobs) { def importer = load("${autobuilder.commonscripts()}/import/importer.groovy") def ArrayList artifactFolders = new ArrayList() - int revisiontotal = 0 for (subJob in subJobs) { def subJobObject = subJob[0] if (subJobObject != null) { @@ -14,14 +13,11 @@ def combineSubjobArtifacts(meta, subJobs) { dir(destFolder) { deleteDir() } - importedmeta = importer.artifactimport(meta, subJobName, subJobNumber, destFolder) - revisiontotal += importedmeta.buildstampinfo.revision + importer.artifactimport(meta, subJobName, subJobNumber, destFolder) artifactFolders.add("${destFolder}/**") } } - def versiongenerator = load("${autobuilder.commonscripts()}/versionnumbering/generate.groovy") - revisiontotal = revisiontotal % (versiongenerator.maxversionnumber() + 1) - return [artifactFolders, revisiontotal] + return artifactFolders } return this; diff --git a/compile/eclipsebuild/eclipseniosbuild.groovy b/compile/eclipsebuild/eclipseniosbuild.groovy new file mode 100644 index 0000000..a808932 --- /dev/null +++ b/compile/eclipsebuild/eclipseniosbuild.groovy @@ -0,0 +1,116 @@ +// Gets the debug and optimization flags. +// Arg1 is "app" or "lib". Returns flags. +// Restore the debug and optimization levels, in case this is a dev machine. +// Arg1 is "app" or "lib". Arg2-3 is flags from getFlags. Returns nothing. +def setFlagsToRelease(NIOSEDS, project, wdir) { + if ( project == "app" ) { + if (isUnix()) { + sh """#!/bin/bash + set -x + cd "${wdir}" + + "${NIOSEDS}/nios2_command_shell.sh" nios2-app-update-makefile --app-dir=. --set-optimization=-O2 --set-debug-level= + """ + } + } + else if ( project == "lib" ) { + if (isUnix()) { + sh """#!/bin/bash + set -x + cd "${wdir}" + + "${NIOSEDS}/nios2_command_shell.sh" nios2-lib-update-makefile --lib-dir=. --set-optimization=-O2 --set-debug-level= + """ + } + } +} + +def remake_and_check(NIOSEDS, wdir) { + if (isUnix()) { + sh """#!/bin/bash + set -x + cd "${wdir}" + + # Use the makefile to clean and build + "${NIOSEDS}/nios2_command_shell.sh" make clean + if [ \$? -ne 0 ]; then exit 1; fi + + # Set the debug and optimization levels to production values + "${NIOSEDS}/nios2_command_shell.sh" make -j12 all + if [ \$? -ne 0 ]; then exit 1; fi + """ + } +} + +def generate_bsp(NIOSEDS, bspfolder) { + if (isUnix()) { + sh """#!/bin/bash + set -x + + "${NIOSEDS}/nios2_command_shell.sh" nios2-bsp-generate-files --bsp-dir "${bspfolder}" --log "${bspfolder}/bsp.log" --settings "${bspfolder}/settings.bsp" + """ + } +} + +def modifylib(NIOSEDS, bspfolder, buildconfig, wdir) { + if (isUnix()) { + sh """#!/bin/bash + set -x + + cd "${wdir}" + + "${NIOSEDS}/nios2_command_shell.sh" nios2-lib-update-makefile --lib-dir=. --set-bsp-dir "${bspfolder}" --set-active-build-config "${buildconfig}" + """ + } +} + +def modifyapp(NIOSEDS, bspfolder, wdir) { + if (isUnix()) { + sh """#!/bin/bash + set -x + + cd "${wdir}" + + "${NIOSEDS}/nios2_command_shell.sh" nios2-app-update-makefile --app-dir=. --set-bsp-dir "${bspfolder}" + """ + } +} + +def dump_elf_info(NIOSEDS, elffile, meta, custominfokeyprefix) { + if (isUnix()) { + def cpu_name = sh(script: """#!/bin/bash + "${NIOSEDS}/nios2_command_shell.sh" nios2-elf-query "${elffile}" --cpu_name + """, + returnStdout: true + ).trim() + meta.addCustomInfo("${custominfokeyprefix}_cpu_name", cpu_name) + def sidp = sh(script: """#!/bin/bash + "${NIOSEDS}/nios2_command_shell.sh" nios2-elf-query "${elffile}" --sidp + """, + returnStdout: true + ).trim() + meta.addCustomInfo("${custominfokeyprefix}_sidp", sidp) + def id = sh(script: """#!/bin/bash + "${NIOSEDS}/nios2_command_shell.sh" nios2-elf-query "${elffile}" --id + """, + returnStdout: true + ).trim() + meta.addCustomInfo("${custominfokeyprefix}_id", id) + def timestamp = sh(script: """#!/bin/bash + "${NIOSEDS}/nios2_command_shell.sh" nios2-elf-query "${elffile}" --timestamp + """, + returnStdout: true + ).trim() + meta.addCustomInfo("${custominfokeyprefix}_timestamp", timestamp) +/* + def sopcinfo = sh(script: """#!/bin/bash + "${NIOSEDS}/nios2_command_shell.sh" nios2-elf-query "${elffile}" --sopcinfo + """, + returnStdout: true + ).trim() + meta.addCustomInfo("${custominfokeyprefix}_sopcinfo", sopcinfo) +*/ + } +} + +return this; \ No newline at end of file diff --git a/file/utils.groovy b/file/utils.groovy deleted file mode 100644 index 0ffa47c..0000000 --- a/file/utils.groovy +++ /dev/null @@ -1,16 +0,0 @@ - -def lineendings = load("${autobuilder.commonscripts()}/platform/lineendings.groovy") - -// Get current contents of given file and optionally add a newline string/character; If file doesn't exist, return default contents -def currentContents(file, newline = "${nl}", defaultContents = "") { - def contents = "" - if (fileExists("${file}")) { - contents = readFile(file: "${file}").trim() + newline - } - else { - contents = defaultContents - } - return contents -} - -return this; diff --git a/import/importer.groovy b/import/importer.groovy index 4d24d30..1f89426 100644 --- a/import/importer.groovy +++ b/import/importer.groovy @@ -1,18 +1,23 @@ +versiongenerator = load("${autobuilder.commonscripts()}/versionnumbering/generate.groovy") -def artifactimport(meta, String jenkinsjob, int buildnumber, String destpath, String filter = '**', boolean fingerprint = false) { +def artifactimport(meta, String jenkinsjob, int buildnumber, String destpath, String filter = '**', String excludes = '', boolean fingerprint = false) { copyArtifacts( filter: filter, + excludes: excludes, fingerprintArtifacts: fingerprint, projectName: jenkinsjob.trim(), selector: specific(buildnumber.toString()), target: destpath ) - return meta.importrelated(destpath) + def importedmeta = meta.importrelated(destpath) + meta.buildstampinfo.changerevision(versiongenerator.incrementrevision(meta.buildstampinfo.revision, importedmeta.buildstampinfo.revision)) + return importedmeta } -def artifactimport(meta, String jenkinsjob, String buildselector, String destpath, String filter = '**', boolean fingerprint = false) { +def artifactimport(meta, String jenkinsjob, String buildselector, String destpath, String filter = '**', String excludes = '', boolean fingerprint = false) { copyArtifacts( filter: filter, + excludes: excludes, fingerprintArtifacts: fingerprint, projectName: jenkinsjob.trim(), selector: [ @@ -21,7 +26,9 @@ def artifactimport(meta, String jenkinsjob, String buildselector, String destpat ], target: destpath ) - return meta.importrelated(destpath) + def importedmeta = meta.importrelated(destpath) + meta.buildstampinfo.changerevision(versiongenerator.incrementrevision(meta.buildstampinfo.revision, importedmeta.buildstampinfo.revision)) + return importedmeta } return this; diff --git a/install/installhelper.groovy b/install/installhelper.groovy index f523799..0155c7f 100644 --- a/install/installhelper.groovy +++ b/install/installhelper.groovy @@ -1,30 +1,21 @@ // Given details about artifacts to import and details of installers to build, import artifacts that are required -def artifactsImporter(artifactDetails, installerDetails) { +def Map artifactsImporter(meta, artifactDetails, installerDetails) { artifactFetched = [:] + def importer = load("${autobuilder.commonscripts()}/import/importer.groovy") for (installer in toBuild) { def artifactKey = installerDetails.get(installer)[0] - //echo "To build: ${installer} use artifactKey: ${artifactKey}" - (sourceProject, destFolder, toCopy, notToCopy, binariesFolders) = artifactDetails.get(artifactKey) - env.importDest = destFolder + (sourceProject, sourceselector, destFolder, toCopy, notToCopy, binariesFolders) = artifactDetails.get(artifactKey) if (artifactFetched.get(artifactKey) == null) { - //echo "Artifact info: ${artifactInfo}" - copyArtifacts excludes: notToCopy, filter: toCopy, fingerprintArtifacts: true, projectName: "${sourceProject}", selector: lastSuccessful(), target: "${destFolder}" - def componentVersionFolder = "${WORKSPACE}\\version\\version_${artifactKey}" - def folderToCopy = "${destFolder}\\version" - echo "Copying from: ${folderToCopy} to: ${componentVersionFolder}" - fileOperations([folderCopyOperation(destinationFolderPath: componentVersionFolder, sourceFolderPath: folderToCopy)]) - //fileOperations([fileCopyOperation(excludes: '', flattenFiles: false, includes: filesToCopy, targetLocation: componentVersionFolder )]) - def gh = load("${autobuilder.commonscripts()}/versioncontrol/git.groovy") - artifactVersion = gh.getSHAFromVersion("${destFolder}/version") - artifactFetched.put(artifactKey, artifactVersion) + def importmeta = importer.artifactimport(meta, sourceProject, sourceselector, destFolder, toCopy, notToCopy, true) + artifactFetched.put(artifactKey, importmeta) } } return artifactFetched } // Export any required binaries to the /bin folder -def exportBinaries(artifactDetails, installerDetails) { +def placeBinaries(artifactDetails, installerDetails) { for (installer in toBuild) { (artifactSet, targetFolder, executionPath, ISMprojectFile, installerVariant, exportBinaries) = installerDetails.get(installer) if (exportBinaries) { diff --git a/meta/folder.groovy b/meta/folder.groovy index 643e203..15f77d0 100644 --- a/meta/folder.groovy +++ b/meta/folder.groovy @@ -605,8 +605,8 @@ class MetaInfo extends GISJsonSerialised { return METAFOLDERNAME } - String generateartifacts(ArrayList releasedfromhere = new ArrayList(), - ArrayList releasedfromsubmeta = new ArrayList(), + String generateartifacts(ArrayList releasedfromhere = new ArrayList(), // These items are recorded in meta as released from here + ArrayList releasedfromsubmeta = new ArrayList(), // These items are not recorded in meta as released from here String metafilepath ="${METAFOLDERNAME}/${METAFILENAME}" ) { def String artifactlist = METAARTIFACTS diff --git a/publish/do.groovy b/publish/do.groovy new file mode 100644 index 0000000..e280c0c --- /dev/null +++ b/publish/do.groovy @@ -0,0 +1,124 @@ +markunstable = false +unstablereason = "" + +summaryfolder = "${WORKSPACE}/summary" +summaryfile = "${summaryfolder}/summary.txt" +summarystring = "" +releaserepofolder = "${WORKSPACE}/releaserepos" +tempfolder = "${WORKSPACE}/temp" + +def resetfolders() { + dir(summaryfolder) { + deleteDir() + } + dir(releaserepofolder) { + deleteDir() + } + dir(tempfolder) { + deleteDir() + } +} + +def preconditions() { + markunstable = false + unstablereason = "" + summarystring = "" + writeFile(file: summaryfile, text: "Publish summary: \n") +} + +def setunstable(String reason) { + markunstable = true + unstablereason = reason +} + +def summaryappend(String summary) { + def String currentsummarycontents = readFile(file: summaryfile) + writeFile(file: summaryfile, text: currentsummarycontents + summary) + summarystring += summary +} + +gh = load("${autobuilder.commonscripts()}/versioncontrol/git.groovy") +def getcomponentartifacts(releaseinfo, String repofolder, String tempfolder) { + // Copy relevant artifacts to temp folder + summaryappend("Artifacts: ") + + def releasemeta = releaseinfo.meta + def String componentURL = releasemeta.releaseinfo.releaserepoURL + def String revision = "refs/tags/${releasemeta.buildstampinfo.buildstamp}" + def publishableitems = releasemeta.publishableinfo + def ArrayList publishablePaths = new ArrayList() + if (publishableitems.size() > 0) { + for (publishableitem in publishableitems) { + publishablePaths.add(publishableitem.filepath) + summaryappend("${publishableitem.filepath},") + } + gh.gitCheckout(componentURL, revision, repofolder, "", 1, true, publishablePaths) // Shallow clone + } + else { + summaryappend("None ") + } +} + +def publish(String customer) { + summaryappend(" FTP operations: ") + + def String FTP_CLIENT_LOCATION='ftp' + def String FTP_URL='ie1.hostedftp.com' + def String FTP_USER='ftp@globalinkjetsystems.com' + def String FTP_CUSTOMER_ROOT="/Customers/${customer}" + def String FTP_PASSWORD='ramshorn42' + dir(releaserepofolder) { + summaryappend("FTP operations: Transferring to ${FTP_CUSTOMER_ROOT}") + sh """#!/bin/bash + ncftpput -u ${FTP_USER} -p ${FTP_PASSWORD} -R ${FTP_URL} "${FTP_CUSTOMER_ROOT}" . + """ + summaryappend(", Transferred ") + } +} + +def recallcomponent(releaseinfo, String softwarerelease) { + def releasemeta = releaseinfo.meta + def String uniquefolder = "Software/${PRODUCT_NAME} ${software_release}/${releasemeta.productinfo.productname}_${releasemeta.productinfo.subcomponentname}" + def String uniquefolderforrepo = "${releaserepofolder}/${uniquefolder}" + def String uniquefoldertemp = "${tempfolder}/${uniquefolder}" + + summaryappend("${releasemeta.productinfo.productname} ${releasemeta.productinfo.subcomponentname}: ") + + getcomponentartifacts(releaseinfo, uniquefolderforrepo, uniquefoldertemp) + + summaryappend("\n") +} + +def stripgithistory() { + echo "Stripping git history out of ${releaserepofolder}" + dir(releaserepofolder) { + sh """#!/bin/bash + pwd + find . -type d -name ".git" | xargs -iXX rm -rvf XX + find . -name ".gitignore" | xargs -iXX rm -rvf XX + find . -name ".gitmodules" | xargs -iXX rm -rvf XX + find . -iname ".gitattributes" | xargs -iXX rm -rvf XX + """ + } +} + +def publishhierarchy(releasemeta, String customer, String softwarerelease, String maxdepth) { + int md = maxdepth.toInteger() + resetfolders() + preconditions() + + // Walk the meta information to a max depth, looking for artifacts to import for release + componentReleaseInfo = releasemeta.releasewalkerunique(md) + + // For each component + for (key in componentReleaseInfo.keySet()) { + def releaseinfo = componentReleaseInfo[key] + recallcomponent(releaseinfo, softwarerelease) + } + stripgithistory() + publish(customer) + + return [summarystring, markunstable, unstablereason] +} + +return this; diff --git a/publish/publish.groovy b/publish/publish.groovy new file mode 100644 index 0000000..8ed7aa8 --- /dev/null +++ b/publish/publish.groovy @@ -0,0 +1,90 @@ +pipeline { + agent { label "${AGENT_LABEL}" } + stages { + stage('Initial setup') { + steps { + script { + autobuilderscript = load("${WORKSPACE}/autobuild/Common_scripts/autobuilder.groovy") + meta = autobuilderscript.start(this, PRODUCT_NAME, SUBCOMPONENT_NAME, JIRA_KEY, RELEASE_REPO) + } + } + } + stage('Clean folders') { + steps { + script { + cleanfolders = [ + ] + cleaner = load("${autobuilder.commonscripts()}/clean/clean.groovy") + cleaner.clean(cleanfolders) + } + } + } + stage('Checkout release repo') { + steps { + script { + configurationhelper = autobuilder.configurationhelper() + + SOURCEURL = RELEASE_REPO + SOURCEREVISION = "refs/tags/${SOFTWARE_RELEASE}" + SOURCEDIR = "${WORKSPACE}/whole" + SOURCEROOTDIR = 'whole' + configurationhelper.gitCheckoutAndRegister(meta, 'whole', SOURCEURL, SOURCEREVISION, SOURCEDIR, SOURCEROOTDIR, 0, false) + } + } + } + stage('Get release artifact meta') { + steps { + script { + def mfs = autobuilderscript.getmetafolderscript() + releasemeta = mfs.metafromfolder(SOURCEDIR) + } + } + } + stage('Publish components') { + steps { + script { + def publisher = load("${autobuilder.commonscripts()}/publish/do.groovy") + MAX_META_DEPTH='2' + (summarystring, markunstable, unstablereason) = publisher.publishhierarchy(releasemeta, CUSTOMER, SOFTWARE_RELEASE, MAX_META_DEPTH) + if (markunstable) { + env.unstablereason = unstablereason + currentBuild.result = 'UNSTABLE' + } + } + } + } + stage('Archiving artifacts') { + steps { + script { + def artifactlist = meta.generateartifacts() + archiveArtifacts "summary/**,${artifactlist}" + } + } + } + stage('Summarise') { + steps { + script { + echo "Summary:\n${summarystring}\n" + if (env.unstablereason) { + echo "Instability reason: ${env.unstablereason}" + } + } + } + } + } + post { + always { + echo 'Post-build' + } + failure { + echo 'Failed build' + } + unstable { + echo 'Unstable build' + } + success { + echo 'Succeeded build' + } + } +} + diff --git a/release/do.groovy b/release/do.groovy index 169c292..85753e6 100644 --- a/release/do.groovy +++ b/release/do.groovy @@ -140,8 +140,18 @@ def boolean checkforchange(buildmeta, previousreleasemeta) { String buildsha = buildmeta.gitinfo.gitrevision String previoussha = previousreleasemeta.gitinfo.gitrevision - def boolean changed = (buildsha != previoussha) - echo "buildsha: ${buildsha} previoussha: ${previoussha} changed: ${changed}" + def boolean shachanged = (buildsha != previoussha) + echo "buildsha: ${buildsha} previoussha: ${previoussha} changed: ${shachanged}" + + String buildstamp = buildmeta.buildstampinfo.buildstamp + String previousbuildstamp = previousreleasemeta.buildstampinfo.buildstamp + + def boolean buildstampchanged = (buildstamp != previousbuildstamp) + echo "buildstamp: ${buildstamp} previousbuildstamp: ${previousbuildstamp} changed: ${buildstampchanged}" + + def boolean changed = (shachanged | buildstampchanged) + echo "changed: ${changed}" + return changed } diff --git a/release/release.groovy b/release/release.groovy new file mode 100644 index 0000000..828f1ff --- /dev/null +++ b/release/release.groovy @@ -0,0 +1,87 @@ +pipeline { + agent { label "${AGENT_LABEL}" } + stages { + stage('Initial setup') { + steps { + script { + autobuilderscript = load("${WORKSPACE}/autobuild/Common_scripts/autobuilder.groovy") + meta = autobuilderscript.start(this, PRODUCT_NAME, SUBCOMPONENT_NAME, JIRA_KEY, RELEASE_REPO) + } + } + } + stage('Clean exports') { + steps { + script { + cleanfolders = [ + "${WORKSPACE}/build_artifacts", + ] + cleaner = load("${autobuilder.commonscripts()}/clean/clean.groovy") + cleaner.clean(cleanfolders) + } + } + } + stage('Get build artifact meta') { + steps { + script { + BUILD_ARTIFACTS = "${WORKSPACE}/build_artifacts" + copyArtifacts( + filter: 'meta/**', + projectName: BUILD_JOB, + selector: [ + $class: 'ParameterizedBuildSelector', + parameterName: BUILD_JOB_SELECTOR + ], + target: BUILD_ARTIFACTS + ) + def mfs = autobuilderscript.getmetafolderscript() + buildmeta = mfs.metafromfolder(BUILD_ARTIFACTS) + } + } + } + stage('Release components') { + steps { + script { + def releaser = load("${autobuilder.commonscripts()}/release/do.groovy") + (summarystring, markunstable, unstablereason) = releaser.releasehierarchy(buildmeta, MAX_META_DEPTH, OTHER_RELEASE_TAGS, DRY_RUN_PUSH) + if (markunstable) { + env.unstablereason = unstablereason + currentBuild.result = 'UNSTABLE' + } + } + } + } + stage('Archiving artifacts') { + steps { + script { + def artifactlist = meta.generateartifacts() + archiveArtifacts "summary/**,${artifactlist}" + } + } + } + stage('Summarise') { + steps { + script { + echo "Summary:\n${summarystring}\n" + if (env.unstablereason) { + echo "Instability reason: ${env.unstablereason}" + } + } + } + } + } + post { + always { + echo 'Post-build' + } + failure { + echo 'Failed build' + } + unstable { + echo 'Unstable build' + } + success { + echo 'Succeeded build' + } + } +} + diff --git a/versioncontrol/git.groovy b/versioncontrol/git.groovy index cb9354b..8bd7968 100644 --- a/versioncontrol/git.groovy +++ b/versioncontrol/git.groovy @@ -1,3 +1,7 @@ +import hudson.plugins.git.* +import hudson.plugins.git.extensions.* +import hudson.plugins.git.extensions.impl.* + clh = load("${autobuilder.commonscripts()}/commandline/commandline.groovy") String getGitInfo(String workingSetRootPath) { @@ -6,7 +10,16 @@ String getGitInfo(String workingSetRootPath) { } } -def gitCheckout(String gitURL, String revision, String targetDir, String repoRoot = "", int cloneDepth = 1, boolean shallowClone = true) { +@NonCPS +def SparseCheckoutPaths sparsecheckoutconfig(ArrayList paths) { + ArrayList sparsecheckoutpaths = new ArrayList() + for (path in paths) { + sparsecheckoutpaths.add(new SparseCheckoutPath(path)) + } + return new SparseCheckoutPaths(sparsecheckoutpaths) +} + +def gitCheckout(String gitURL, String revision, String targetDir, String repoRoot = "", int cloneDepth = 1, boolean shallowClone = true, ArrayList sparseitemlist = new ArrayList()) { reporootenv = env.REPO_ROOT if (reporootenv != null && repoRoot != "") { reporootpath = "${reporootenv.trim()}/${repoRoot}" @@ -28,7 +41,8 @@ def gitCheckout(String gitURL, String revision, String targetDir, String repoRoo [$class: 'CleanBeforeCheckout'], [$class: 'CloneOption', depth: cloneDepth, noTags: false, reference: reporootpath, shallow: shallowClone, timeout: 120], [$class: 'CheckoutOption', timeout: 120], - [$class: 'RelativeTargetDirectory', relativeTargetDir: targetDir] + [$class: 'RelativeTargetDirectory', relativeTargetDir: targetDir], + sparsecheckoutconfig(sparseitemlist) ], submoduleCfg: [], ]) diff --git a/versionnumbering/do.groovy b/versionnumbering/do.groovy index 9b4a42e..666aee3 100644 --- a/versionnumbering/do.groovy +++ b/versionnumbering/do.groovy @@ -1,17 +1,20 @@ def stamp(convertdetails) { for (convertdetail in convertdetails) { - filetoconvert = convertdetail[0] - pattern = convertdetail[1] - replacement = convertdetail[2] + def filetoconvert = convertdetail[0] + def pattern = convertdetail[1] + def replacement = convertdetail[2] + //echo "Converting any instances of pattern: ${pattern} with replacement: ${replacement} in file: ${filetoconvert}" + def stampscript = "${autobuilder.commonscripts()}/versionstamping/versionstamper.py" + //echo "Using python: ${PYTHON} and script: ${stampscript}" if (isUnix()) { sh """ - "${PYTHON}" -u "${autobuilder.commonscripts()}/versionstamping/versionstamper.py" -f "${filetoconvert}" -p "${pattern}" -s "${replacement}" + "${PYTHON}" -u "${stampscript}" -f "${filetoconvert}" -p "${pattern}" -s "${replacement}" """ } else { bat """ - "%${PYTHON}%" -u "%${autobuilder.commonscripts()}%\\versionstamping\\versionstamper.py" -f "%${filetoconvert}%" -p "%${pattern}%" -s "%${replacement}%" + "${PYTHON}" -u "${stampscript}" -f "${filetoconvert}" -p "${pattern}" -s "${replacement}" """ } } diff --git a/versionnumbering/generate.groovy b/versionnumbering/generate.groovy index ae7e5f4..7e5568a 100644 --- a/versionnumbering/generate.groovy +++ b/versionnumbering/generate.groovy @@ -136,4 +136,10 @@ String generate(meta, String sourcerevision, String sourcepath, int basebuildnum return buildstamp } +int incrementrevision(int current, int increment) { + def int newrevision = (current + increment) % (maxversionnumber() + 1) + echo "Current revision: ${current} Increment: ${increment} New revision: ${newrevision}" + return newrevision +} + return this; \ No newline at end of file diff --git a/versionnumbering/versioninfo.py b/versionnumbering/versioninfo.py deleted file mode 100644 index 3d2a80d..0000000 --- a/versionnumbering/versioninfo.py +++ /dev/null @@ -1,180 +0,0 @@ -# encoding: utf-8 -''' -versionnumbering -- shortdesc - -versionnumbering generates a version folder with a common set of version information files in it - -@author: dan - -@copyright: 2017 Global Inkjet Systems Ltd. All rights reserved. -''' -import os -import sys -import shutil -import subprocess -import re -import datetime - -from argparse import ArgumentParser -from argparse import RawDescriptionHelpFormatter - -__all__ = [] -__version__ = 0.1 -__date__ = '2017-11-29' -__updated__ = '2017-11-29' - -# Handle: -# origin/master -# origin/2.0.x -def getVersionPrefix(sourcebranch): - print("Determining version number prefix from source branch name: {0}".format(sourcebranch)) - - defaultversionprefix = "1.30000.0." - mastertypeversionprefix = "1.20000.0." - thirdpartyversionprefix = "1.25000.0." - splits = sourcebranch.split('/') - if len(splits) < 1: - print("Source branch name is invalid. Defaulting to: {0}".format(defaultversionprefix)) - return defaultversionprefix - - sourcebranch = splits[-1] - - if sourcebranch.lower().find("master") != -1: # Special case - return mastertypeversionprefix - - splits2 = re.split(r'(\d+)', sourcebranch) - splits = [] - hasdot = False - for split in splits2: - if split.isdigit(): - splits.append(split) - if split == ".": - hasdot = True - - if not hasdot: - print("Source branch name has not dots in it (eg. 1.9.2). Defaulting to: {0}".format(thirdpartyversionprefix)) - return thirdpartyversionprefix - - versionprefix = "" - if len(splits) < 1: - print("This source branch name has no numbers in its name so defaulting to: {0}".format(defaultversionprefix)) - versionprefix = defaultversionprefix - else: - splitnumbercount = 0 - isIntermediateReleaseBranch = False - for split in splits: - if split.isdigit(): - versionprefix += split + "." - splitnumbercount += 1 - else: - if split == "x": - isIntermediateReleaseBranch = True - break - if splitnumbercount > 2: - break - if splitnumbercount == 0: - print("No leading numbers were found in source branch name so defaulting to: {0}".format(defaultversionprefix)) - versionprefix = defaultversionprefix - else: - if isIntermediateReleaseBranch: - versionprefix = mastertypeversionprefix - elif splitnumbercount == 1: - versionprefix += "0.0." - elif splitnumbercount == 2: - versionprefix += "0." - - print("Determined version prefix to be: {0}".format(versionprefix)) - return versionprefix - -def writeversionfiles(versionfolder, versionprefix, gitrevisioncount, gitrevision, remoteinfo, remoteurl, buildstamp): - with open(os.path.join(versionfolder, "prefix.txt"), 'w') as f: - f.write(versionprefix) - - with open(os.path.join(versionfolder, "revision.txt"), 'w') as f: - f.write(str(gitrevisioncount)) - - with open(os.path.join(versionfolder, "gitrevision.txt"), 'w') as f: - f.write(gitrevision) - - with open(os.path.join(versionfolder, "remoteinfo.txt"), 'w') as f: - f.write(remoteinfo) - - with open(os.path.join(versionfolder, "remoteurl.txt"), 'w') as f: - f.write(remoteurl) - - with open(os.path.join(versionfolder, "buildstamp.txt"), 'w') as f: - f.write(buildstamp) - - buildstampcommasep = buildstamp.replace(".", ",") - with open(os.path.join(versionfolder, "buildstampcommasep.txt"), 'w') as f: - f.write(buildstampcommasep) - - with open(os.path.join(versionfolder, "builddate.txt"), 'w') as f: - f.write(str(datetime.datetime.now())) - -def main(argv=None): # IGNORE:C0111 - '''Command line options.''' - - if argv is None: - argv = sys.argv - else: - sys.argv.extend(argv) - - program_name = os.path.basename(sys.argv[0]) - program_version = "v%s" % __version__ - program_build_date = str(__updated__) - program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date) - program_shortdesc = __import__('__main__').__doc__.split("\n")[1] - program_license = '''%s - - Created by dan on %s. - Copyright 2017 Global Inkjet Systems Ltd. All rights reserved. - - Distributed on an "AS IS" basis without warranties - or conditions of any kind, either express or implied. - -USAGE -''' % (program_shortdesc, str(__date__)) - - try: - # Setup argument parser - parser = ArgumentParser(description=program_license, formatter_class=RawDescriptionHelpFormatter) - parser.add_argument("-s", "--sourcebranch", dest="sourcebranch", action="store", default="origin/master", help="source branch name to discover version number [default: %(default)s]") - parser.add_argument("-v", "--versionfolder", dest="versionfolder", action="store", default="version", help="version folder to be created [default: %(default)s]") - parser.add_argument("-g", "--gitroot", dest="gitrootfolder", action="store", default="GitRepository", help="root path of source files [default: %(default)s]") - parser.add_argument("-b", "--baseversionnumber", dest="baseversionnumber", action="store", default=int(1000), help="base git version number [default: %(default)s]") - - # Process arguments - args = parser.parse_args() - - try: - sourcebranch = args.sourcebranch - versionfolder = args.versionfolder - gitrootfolder = args.gitrootfolder - baseversionnumber = args.baseversionnumber - - print("Source branch:", sourcebranch, "version folder:", versionfolder, "Git root:", gitrootfolder) - print("Base version number:", baseversionnumber) - - (gitrevisioncount, gitrevision, remoteinfo, remoteurl) = getGitRevision(gitrootfolder, baseversionnumber) - - versionprefix = getVersionPrefix(sourcebranch) - - buildstamp = versionprefix + str(gitrevisioncount) - print("Build stamp is: {0}".format(buildstamp)) - - writeversionfiles(versionfolder, versionprefix, gitrevisioncount, gitrevision, remoteinfo, remoteurl, buildstamp) - - return 0 - except Exception as e: - print("Error while creating version info:", e.__repr__()) - return 1 - - except Exception as e: - indent = len(program_name) * " " - print(program_name + ": " + repr(e) + "\n") - print(indent + " for help use --help") - return 2 - -if __name__ == "__main__": - sys.exit(main())