Eldad Assis
Eldad Assis

Reputation: 11045

Jenkins git tag as parameter sorted by date

In Jenkins, I need to have the Git Parameter functionality but with tag creation time sort option (which is not supported there).

I have implemented a solution which I'll post as an answer to help others that seek such functionality, but I'd like to hear comments and opinions on it.

Feel free to suggest more ideas.

Upvotes: 2

Views: 1352

Answers (1)

Eldad Assis
Eldad Assis

Reputation: 11045

Currently, to solve this, I used the Dynamic Parameter Plug-in with some groovy I wrote as a Scriptler.

The idea is to cache a local copy of the repository in a temporary location (which can be reused later) and query it with some git log command.

The code I have is for a Windows server, but can easily be changed to support Linux.

def cloneDirName = "c:\\temp\\${repoName}"

def gitClone = "git clone --bare ${gitURL} ${cloneDirName}"
def gitPull = "cmd.exe /c cd ${cloneDirName} & git fetch origin +refs/heads/*:refs/heads/* --prune"
def gitLogTags = "cmd.exe /c cd ${cloneDirName} & git log --date-order --tags --simplify-by-decoration --pretty=format:%D"

def folder = new File( cloneDirName )

def proc
def action
def text
def list = []


if( !folder.exists() ) {
    folder.mkdirs()
    proc = gitClone.execute()
    action = "cloning"
} else {
    // Just update the repo
    proc = gitPull.execute()
    action = "pulling"
}

//println "${action}..."

proc.waitFor()

if ( proc.exitValue() != 0 ) {
    text = "ERROR {$action}"
}

action = "getting tags"
proc = gitLogTags.execute()
proc.waitFor()

text = proc.in.text

// For debug - uncomment and run
//println "${text}"
//println "\n\n***\n\n"

if ( proc.exitValue() != 0 ) {
    text = "ERROR {$action}"
    list.add(text)
} else {
    text = text.replace("\n", ",")
    def m = text =~ /tag: [^,]+/
    m.each {
        // For debug - uncomment and run
        // println it
        list.add(it.replace("tag:", ""))
    }
}

// For debug - uncomment and run
//println "\n\n***\n\n"
list.each { println it }

This setup works very well, but I was wondering if there are other suggestions.
My main concern is the need to pre-fetch the repository (can take time for large repositories).

I hope this helps.

Upvotes: 2

Related Questions