Class: ChefCLI::PolicyfileServices::CleanPolicies

Inherits:
Object
  • Object
show all
Defined in:
lib/chef-cli/policyfile_services/clean_policies.rb

Defined Under Namespace

Classes: Orphan

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config: nil, ui: nil) ⇒ CleanPolicies

Returns a new instance of CleanPolicies.



31
32
33
34
# File 'lib/chef-cli/policyfile_services/clean_policies.rb', line 31

def initialize(config: nil, ui: nil)
  @chef_config = config
  @ui = ui
end

Instance Attribute Details

#chef_configObject (readonly)

Returns the value of attribute chef_config.



28
29
30
# File 'lib/chef-cli/policyfile_services/clean_policies.rb', line 28

def chef_config
  @chef_config
end

#uiObject (readonly)

Returns the value of attribute ui.



29
30
31
# File 'lib/chef-cli/policyfile_services/clean_policies.rb', line 29

def ui
  @ui
end

Instance Method Details

#http_clientObject



77
78
79
80
81
# File 'lib/chef-cli/policyfile_services/clean_policies.rb', line 77

def http_client
  @http_client ||= Chef::ServerAPI.new(chef_config.chef_server_url,
    signing_key_filename: chef_config.client_key,
    client_name: chef_config.node_name)
end

#orphaned_policiesObject



63
64
65
66
67
68
69
70
71
# File 'lib/chef-cli/policyfile_services/clean_policies.rb', line 63

def orphaned_policies
  policy_lister.policies_by_name.keys.inject([]) do |orphans, policy_name|
    orphans + policy_lister.orphaned_revisions(policy_name).map do |revision_id|
      Orphan.new(policy_name, revision_id)
    end
  end
rescue => e
  raise PolicyfileCleanError.new("Failed to list policies for cleaning.", e)
end

#policy_listerObject



73
74
75
# File 'lib/chef-cli/policyfile_services/clean_policies.rb', line 73

def policy_lister
  @policy_lister ||= Policyfile::Lister.new(config: chef_config)
end

#runObject



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
# File 'lib/chef-cli/policyfile_services/clean_policies.rb', line 36

def run
  revisions_to_remove = orphaned_policies

  if revisions_to_remove.empty?
    ui.err("No policy revisions deleted")
    return true
  end

  results = revisions_to_remove.map do |policy|
    [ remove_policy(policy), policy ]
  end

  failures = results.select { |result, _policy| result.is_a?(Exception) }

  unless failures.empty?
    details = failures.map do |result, policy|
      "- #{policy.policy_name} (#{policy.revision_id}): #{result.class} #{result}"
    end

    message = "Failed to delete some policy revisions:\n" + details.join("\n") + "\n"

    raise PolicyfileCleanError.new(message, MultipleErrors.new("multiple errors"))
  end

  true
end