簡體   English   中英

如何通過 Jenkins groovy 腳本刪除 Jenkins 工作區中的特定文件

[英]how to delete a particular file in Jenkins workspace via Jenkins groovy script

我有一個 Jenkins 管道,它通過 SCM 觸發一個 Jenkins groovy 腳本,這個腳本將創建一個文件(如果文件不存在)並寫入,否則它將更新文件並做一些事情,這個文件需要被刪除。

下面是創建、寫入和更新文件的代碼。

node(node_label){
     if (fileExists ( file_path+'/'+file_name ) ){
          def readContent = readFile file_path+'/'+file_name
          writeFile file: file_path+'/'+file_name, text: readContent+'\r\n'+data
     }else{
          writeFile file: file_path+'/'+file_name, text:data
     }
 }

在做了一些事情之后,我需要刪除這個文件,我嘗試如下刪除它,但它不起作用。

def Delfile = new File(path+'/'+file_name)
Delfile.delete()

我有以下手動工作區清理,所以正如你提到的,它應該也可以工作,請檢查以下內容。

我假設您可能沒有正確獲取文件路徑

//load jobs
def jobs = Jenkins.instance.getAllItems(Job.class)

//iterate over
for(job in jobs) {

//seems like they dont have workspace
  if(job instanceof hudson.model.ExternalJob){
    continue
  }


     String workspace = null

     //pipelines dont have workspace
     if(job instanceof org.jenkinsci.plugins.workflow.job.WorkflowJob){
       println ("workflow job, not cleaning")   
       continue
     }

     try{
       workspace = job.workspace
     }catch(Exception e){
         //already clean eg.
       println ("no workspace, not cleaning")   
       workspace = null
     }

     if(workspace != null){
       //creation of the workspace and modules folder
       //again not sure, but sometimes was failing due boolean ..
       if(workspace instanceof java.lang.Boolean){
        println "cant cleanup"
        continue
       }

       File folder = new File(workspace) 

       //Check if the Workspace folder really exists
       if(folder!=null && folder.exists()){ 
         //workspace cleanup

         //get files
         File[] files = null
         try{
          files=new File(workspace).listFiles().sort(){
             //println it.name  

             if(!it.isFile()){
               it.deleteDir()
             }else{
               it.delete()
             }
           }
         }catch(Exception e){
            println "cant clean: " + workspace          
         } 

       }else{
        println "workspace is not existing, not cleaning"
       }  
   }
} 

所以,清理的核心是:

  //get files
         File[] files = null
         try{
          files=new File(workspace).listFiles().sort(){
             //println it.name  

             if(!it.isFile()){
               it.deleteDir()
             }else{
               it.delete()
             }
           }
         }catch(Exception e){
            println "cant clean: " + workspace          
         } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM