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

Chef Cookbook: filter a list of files to delete

我有一个变量存储应该保留的文件

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

服务器上存在以下文件

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

我想删除那些不是默认的文件['keep']['files'],即c.txt和d.txt
但我无法弄清楚如何获取要删除的文件列表。

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

您只需从文件列表数组中减去 keep 数组,这将为您留下要删除的文件名数组。 例如

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

所以你可以做类似的事情

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

但您可能想先对数组进行排序,代码未经测试但应该没问题