Home > Enterprise >  Jenkins groovy regex pattern search and match in commit message not working as expected
Jenkins groovy regex pattern search and match in commit message not working as expected

Time:05-09

I'm working with this pipeline where running tests from a commit message should be an option.

I'm a novice in groovy and regex, but I have managed to get matches from commit messages and can run my tests just fine. The only problem is, there can be nothing else written in the commit message, or else it fails.

I want to be able to write which tests I want to run pretty much anywhere in the commit message. Or maybe as the first thing at the top, then the rest of message after that.

A commit message could look like..

jenkins:BASE_TEST, RADIO_TEST, CRYPTO_TEST

blablabla

My script looks like this:

def testPattern = ~/(?:^|[\r\n] )jenkins:([, a-zA-Z_] )(?:$|[\r\n] )/
for (int i = 0; i < currentBuild.changeSets.size(); i  ) 
{
  //entries -> author, timestamp, msg etc.
  def entries = currentBuild.changeSets[i].items
  for (int j = 0; j < entries.length; j  ) 
  {
    def testMatcher = testPattern.matcher(entries[j].msg)

    if (testMatcher.matches()) 
    {
      def testList = testMatcher.group(1).tokenize(',')
      for (int k = 0; k < testList.size(); k  ) 
      {
        testList[k] = testList[k].replaceAll("\\s", "")

        switch (testList[k]) 
        {
          case 'RUN_ALL_TESTS':
            env.SPREADING_FACTOR_TEST = true
            env.RADIO_TEST = true
            env.BASE_TEST = true
            env.DEVELOP_TEST = true
            env.CRYPTO_TEST = true
            break
          case 'SPREADING_FACTOR_TEST':
            env.SPREADING_FACTOR_TEST = true
            break
          case 'RADIO_TEST':
            env.RADIO_TEST = true
            break
          case 'BASE_TEST':
            env.BASE_TEST = true
            break
          case 'DEVELOP_TEST':
            env.DEVELOP_TEST = true
            break
          case 'CRYPTO_TEST':
            env.CRYPTO_TEST = true
            break
          default:
            break
        }
      }
    }
  }
}

I have tried to set multiline in testPattern in multiple ways but i might have done it wrong. I have used very much time in: https://regex101.com/r/43se9W/1

regex101 example

In regex101 it clearly has no problem matching, but my testMatcher.matches() returns false. Hence the problem is that it can't match.

I have tried looking at https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#compile(java.lang.String) but maybe I have implemented it wrong.

CodePudding user response:

So apparently you need to use the find() method instead of matches(), duh.. It works now.

  • Related