繁体   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