Module: Chef::Mixin::FindPreferredFile

Included in:
Provider::RemoteDirectory, Provider::RemoteFile, Provider::Template
Defined in:
lib/chef/mixin/find_preferred_file.rb

Instance Method Summary collapse

Instance Method Details

#find_preferred_file(cookbook_id, file_type, file_name, fqdn, platform, version) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/chef/mixin/find_preferred_file.rb', line 66

def find_preferred_file(cookbook_id, file_type, file_name, fqdn, platform, version)
  file_list = load_cookbook_files(cookbook_id, file_type)
  
  preferences = [
    File.join("host-#{fqdn}", "#{file_name}"),
    File.join("#{platform}-#{version}", "#{file_name}"),
    File.join("#{platform}", "#{file_name}"),
    File.join("default", "#{file_name}")
  ]
  
  file_list_str = file_list.keys.join("\n")
  Chef::Log.debug("Searching for preferred file in\n#{file_list_str}")
  
  preferences.each do |pref|
    Chef::Log.debug("Looking for #{pref}")
    matcher = /^(.+#{pref})$/
    if match = matcher.match(file_list_str)
      return match[1]
    end
  end
  
  raise Chef::Exceptions::FileNotFound, "Cannot find a preferred file for #{file_name}!"
end

#load_cookbook_files(cookbook_id, file_type) ⇒ Object

Raises:

  • (NotFound)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/chef/mixin/find_preferred_file.rb', line 25

def load_cookbook_files(cookbook_id, file_type)
  unless file_type == :remote_file || file_type == :template
    raise ArgumentError, "You must supply :remote_file or :template as the file_type"
  end
  
  cl = Chef::CookbookLoader.new
  cookbook = cl[cookbook_id]
  raise NotFound unless cookbook

  files = Hash.new
  
  cookbook_method = nil
  
  case file_type
  when :remote_file
    cookbook_method = :remote_files
  when :template
    cookbook_method = :template_files
  end
          
  cookbook.send(cookbook_method).each do |rf|
    full = File.expand_path(rf)
    name = File.basename(full)
    case file_type
    when :remote_file
      rf =~ /^.+#{cookbook_id}[\\|\/]files[\\|\/](.+?)[\\|\/]#{name}/
    when :template
      rf =~ /^.+#{cookbook_id}[\\|\/]templates[\\|\/](.+?)[\\|\/]#{name}/
    end
    singlecopy = $1
    files[full] = {
      :name => name,
      :singlecopy => singlecopy,
      :file => full,
    }
  end
  Chef::Log.debug("Preferred #{file_type} list: #{files.inspect}")
  
  files
end