2016-12-20 27 views
5

Tôi cần kiểm tra sự tồn tại của một tệp .exe nhất định trong không gian làm việc của tôi như một phần công việc xây dựng đường ống của tôi. Tôi đã cố gắng sử dụng kịch bản Groovy dưới đây từ Jenkinsfile của tôi để làm như vậy. Nhưng tôi nghĩ rằng lớp File mặc định cố gắng tìm thư mục workspace trên jenkins master và thất bại.Sử dụng FilePath để truy cập không gian làm việc trên slave trong đường ống Jenkins

@com.cloudbees.groovy.cps.NonCPS 
def checkJacoco(isJacocoEnabled) { 

    new File(pwd()).eachFileRecurse(FILES) { it -> 
    if (it.name == 'jacoco.exec' || it.name == 'Jacoco.exec') 
     isJacocoEnabled = true 
    } 
} 

Làm cách nào để truy cập hệ thống tệp trên slave bằng Groovy từ bên trong Jenkinsfile?

Tôi cũng đã thử mã bên dưới. Nhưng tôi nhận được lỗi No such property: build for class: groovy.lang.Binding. Tôi cũng đã cố gắng sử dụng đối tượng người quản lý thay thế. Nhưng nhận được cùng một lỗi.

@com.cloudbees.groovy.cps.NonCPS 
def checkJacoco(isJacocoEnabled) { 

    channel = build.workspace.channel 
    rootDirRemote = new FilePath(channel, pwd()) 
    println "rootDirRemote::$rootDirRemote" 
    rootDirRemote.eachFileRecurse(FILES) { it -> 
     if (it.name == 'jacoco.exec' || it.name == 'Jacoco.exec') { 
      println "Jacoco Exists:: ${it.path}" 
      isJacocoEnabled = true 
    } 
} 

Trả lời

10

Đã cùng một vấn đề, tìm thấy giải pháp này:

import hudson.FilePath; 
import jenkins.model.Jenkins; 

node("aSlave") { 
    writeFile file: 'a.txt', text: 'Hello World!'; 
    listFiles(createFilePath(pwd())); 
} 

def createFilePath(path) { 
    if (env['NODE_NAME'] == null) { 
     error "envvar NODE_NAME is not set, probably not inside an node {} or running an older version of Jenkins!"; 
    } else if (env['NODE_NAME'].equals("master")) { 
     return new FilePath(path); 
    } else { 
     return new FilePath(Jenkins.getInstance().getComputer(env['NODE_NAME']).getChannel(), path); 
    } 
} 
@NonCPS 
def listFiles(rootPath) { 
    print "Files in ${rootPath}:"; 
    for (subPath in rootPath.list()) { 
     echo " ${subPath.getName()}"; 
    } 
} 

Điều quan trọng ở đây là createFilePath() ins't chú thích với @NonCPS vì nó cần truy cập vào biến env. Việc sử dụng @NonCPS sẽ xóa quyền truy cập vào "Độ tốt đường ống", nhưng mặt khác, nó không yêu cầu tất cả các biến cục bộ đều có thể tuần tự hóa được. Sau đó, bạn có thể thực hiện tìm kiếm tệp trong phương thức listFiles().

+2

Đã lưu cuộc sống của tôi :) Cảm ơn !! –

Các vấn đề liên quan