如何通过Jenkins Groovy脚本删除Jenkins工作区中的特定文件

aelbi1ox  于 2022-11-02  发布在  Jenkins
关注(0)|答案(1)|浏览(392)

我有一个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()
y0u0uwnf

y0u0uwnf1#

我有以下手动工作区清理,所以正如你提到的,它应该工作,以及检查下面。
我假设您可能没有正确获取文件路径

//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          
         }

相关问题