Skip to content

Instantly share code, notes, and snippets.

@savornicesei
Last active March 6, 2020 22:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save savornicesei/c9dbafec8339b1e8d18c1d4a6e620baa to your computer and use it in GitHub Desktop.
Save savornicesei/c9dbafec8339b1e8d18c1d4a6e620baa to your computer and use it in GitHub Desktop.
Groovy script for Jenkins that returns the assembly version from a .NET project (SolutionInfo.cs file) and the build time as YYY-MM-DD HH:SS. Can be used to inject variables into the Jenkins build.
import hudson.*
import hudson.model.*
import hudson.remoting.*
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import jenkins.*
import jenkins.model.*
import org.jenkinsci.remoting.*;
def isDebugMode = true
def currentBuild
if(isDebugMode)
{
// for testing, use last build or specific build number
currentBuild = Jenkins.instance.getJob("My_project_name").getLastSuccessfulBuild()
}
else
{
// work with current build
currentBuild = Thread.currentThread()?.executable
}
if(currentBuild == null)
{
throw new Exception('Current build is null!')
return
}
if(currentBuild != null && currentBuild.workspace == null)
{
throw new Exception('Current build workspace is null!')
return
}
println currentBuild.workspace
class FileParser
{
static class FileSearch extends MasterToSlaveFileCallable<String> {
@Override
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
def line
def tokens
def ver
// f and file represent the same thing
f.withReader { reader ->
while ((line = reader.readLine())!=null) {
if(line.contains('AssemblyVersion'))
{
tokens = line.tokenize('"')
ver = tokens[1]
break;
}
}
}
return ver
}
}
}
def searchKey = 'AssemblyVersion'
def version
FilePath file
if(currentBuild.workspace.isRemote())
{
channel = currentBuild.workspace.channel;
file = new FilePath(channel, currentBuild.workspace.toString() + "/Src/SolutionInfo.cs")
} else {
file = new FilePath(new File(currentBuild.workspace.toString() + "/Src/SolutionInfo.cs"))
}
version = file.act(new FileParser.FileSearch())
def map = [:]
map["BUILD_TIMESTAMP"] = currentBuild.getTime().format("YYYY-MMM-DD HH:MM:SS")
map["PRJ_VERSION"] = version
println(map)
return map
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment