简体   繁体   English

Chef Cookbook:过滤要删除的文件列表

[英]Chef Cookbook: filter a list of files to delete

I have a variable storing the files which should be keep我有一个变量存储应该保留的文件

default['keep']['files'] = ['a.txt', 'b.txt']

And bellow files exist on the server并且服务器上存在以下文件

'a.txt', 'b.txt', 'c.txt', 'd.txt'

I want to delete those file which is not in default['keep']['files'], ie c.txt and d.txt我想删除那些不在默认['keep']['files']中的文件,即c.txt和d.txt
but I am not able to figure out how to get the list of the files to be deleted.但我无法弄清楚如何获取要删除的文件列表。

// How should I get the list so that i can loop it?
???.each do |file_name|
  directory "Delete #{file_name}" do
    path my_folder_path
    recursive true
    action :delete
  end
end

You can just subtract keep array from the file list array which will leave you with an array of file names to delete.您可以从文件列表数组中减去保留数组,这将为您留下要删除的文件名数组。 eg例如

a1 = ['file1', 'file2']
a2 = ['file1', 'file2', 'file3', 'file4']
a3 = a2 - a1 #results in a3 => ['file3', 'file4']

So you could do something like所以你可以做类似的事情

files_to_keep = ['a.txt', 'b.txt']
all_files = Dir.entries
files_to_delete = all_files - files_to_keep
files_to_delete.each do |file_name|
  if ! Dir.exist? #Check that the file name is not an actual directory
    # write your code to delete the file named file_name
  end
end

But you might want to sort the arrays first, code is untested but should be fine但是您可能想先对 arrays 进行排序,代码未经测试,但应该没问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM