Class: Chef::Knife::CookbookCleanup

Inherits:
Chef::Knife show all
Defined in:
lib/chef/knife/cookbook_cleanup.rb

Instance Method Summary collapse

Instance Method Details

#runObject



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
65
66
67
68
69
70
71
72
# File 'lib/chef/knife/cookbook_cleanup.rb', line 33

def run
  all_cookbooks = rest.get_rest('/cookbooks?num_versions=all')
  drop_cookbooks = Hash.new
  keep_cookbooks = Hash.new
  all_cookbooks.each do |cb|
    cookbook_name = cb[0]
    sorted_versions = cb[1]["versions"].map{ |v| v["version"] }.sort{ |x, y|Gem::Version.new(x) <=> Gem::Version.new(y) }
    keep_versions = sorted_versions.pop
    dropped_versions = sorted_versions
    drop_cookbooks[cookbook_name] = dropped_versions
    keep_cookbooks[cookbook_name] = keep_versions
  end
  keep_cookbooks.delete_if { |k, v|v.empty? }
  drop_cookbooks.delete_if { |k, v|v.empty? }

  if drop_cookbooks.empty?
    ui.info "No old cookbook versions were found"
    exit 0
  end

  ui.msg ""
  ui.msg "The following cookbook versions will remain on the chef server:"
  ui.msg ""
  ui.msg ui.output(keep_cookbooks)
  ui.msg ""
  ui.msg "The following cookbook versions will be deleted:"
  ui.msg ""
  ui.msg ui.output(drop_cookbooks)
  ui.msg ""
  unless config[:yes]
    ui.confirm("Do you really want to delete these cookbooks? (Y/N) ", false)
  end

  drop_cookbooks.each do |cookbook, versions|
    versions.each do |version|
      rest.delete_rest("cookbooks/#{cookbook}/#{version}")
      ui.info("Deleted cookbook #{cookbook.ljust(25)} [#{version}]")
    end
  end
end