使用Groovy读取文件并将文件内容与管道参数进行比较

时间:2018-02-06 21:54:11

标签: jenkins groovy jenkins-pipeline

我有一个文件file.txt,它是用一些内容创建的,样本如下

 /abc/jenkins/data/jobs/random/workspace/file.txt - With below content 
  ------------------------- 
 [abc, hde, jef ,dgd , 1243, 324# ,23534 ....]
  ==> First step
  id - 1235
  branch - 104
  path - dthdp:/opt/usr/nimb/src/emc/crm/104/mat/1235
  area - crm
  rev - 10
  status - Running

我有一组参数,我从管道输入

  **Sample parameters**
  buildnum - 1235
  prod - crm
  trunk - 104 ... etc 

我正在尝试读取文件并将其数据与参数进行比较并打印"所有参数都匹配"如果

 [ buildnum parameter = id  value in file , prod parameter= area value in file , branch parameter = trunk value in file ] 

任何人都可以帮助如何在groovy中编写它,下面没有工作

    def file = new File(env.WORKSPACE+"/file.txt")
            def lineCount = 0
          file.eachLine { line ->
    def parts = line.split '\n'
              println "parts"
    if ( parts != 'params.buildnum' )
       System.err.println "Failure! Doesnt match with buildnm..."
    if ( parts !=  'params.trunk' )
      System.err.println "Failure! Doesnt match with trunk..."
     lineCount++

1 个答案:

答案 0 :(得分:1)

//just test data from file
def data = ''' 
[abc, hde, jef ,dgd , 1243, 324# ,23534 ....]
  ==> First step
  id - 1235
  branch - 104
  path - dthdp:/opt/usr/nimb/src/emc/crm/104/mat/1235
  area - crm
  rev - 10
  status - Running
  '''
def m = /\s*(\w+)\s*-\s*(.*)/

def reader = new StringReader(data)
//to get reader from file use the following code:
//def reader = new File(FILE_PATH).newReader()

//read lines and keep only valid according to regexp
def lines = reader.readLines().findAll{it=~m}
//convert valid lines into a map
def fmap = lines.collectEntries{ (it=~m).find{true}.with{[it[1],it[2]]} }
//validate value in map against parameter
assert fmap.id == '1235'