Class: Chef::Knife::EnvironmentSync

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

Overview

EnvironmentSync class

Instance Method Summary collapse

Instance Method Details

#compare(env, chef_env, local_env) ⇒ Object



45
46
47
48
49
50
# File 'lib/chef/knife/environment_sync.rb', line 45

def compare(env, chef_env, local_env)
  msg = "--> Checking #{env}".ljust(50)
  opts = config[:abbrev] ? {} : { array_path: true }
  diff = ::HashDiff.diff(chef_env, local_env, opts)
  diff.empty? ? show_success(msg) : show_error(msg, diff)
end

#env_from_chef(env) ⇒ Object



63
64
65
66
67
# File 'lib/chef/knife/environment_sync.rb', line 63

def env_from_chef(env)
  Chef::Environment.load(env).to_hash
rescue Net::HTTPServerException
  ui.error("Environment '#{env}' could not be found on chef server")
end

#env_from_file(env) ⇒ Object



69
70
71
72
73
74
75
76
77
78
# File 'lib/chef/knife/environment_sync.rb', line 69

def env_from_file(env)
  files = find_env_file(env.tr('-', '_'))
  if files.empty?
    ui.error("Environment '#{env}' could not be found on disk")
  elsif files.count > 1
    ui.error("Duplicate file environment for '#{env}'")
  else
    loader.object_from_file(files.first).to_hash
  end
end

#find_env_file(env) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/chef/knife/environment_sync.rb', line 52

def find_env_file(env)
  config_path = Chef::Config[:environment_path]
  env_paths = config_path.is_a?(String) ? [config_path] : config_path
  env_paths.map do |env_path|
    path_glob =
      File.join(Chef::Util::PathHelper.escape_glob_dir(env_path), '**')
    path_glob << "/#{env.gsub(/[_-]/, '{-,_}')}.{json,rb}"
    Dir.glob(path_glob)
  end.flatten
end

#loaderObject



41
42
43
# File 'lib/chef/knife/environment_sync.rb', line 41

def loader
  @loader ||= Core::ObjectLoader.new(Chef::Environment, ui)
end

#runObject



80
81
82
83
84
85
86
87
88
89
90
# File 'lib/chef/knife/environment_sync.rb', line 80

def run
  envs = name_args.empty? ? Chef::Environment.list.keys : name_args
  envs.delete('_default')
  envs.each do |env|
    chef_env = env_from_chef(env)
    local_env = env_from_file(env)
    next if chef_env.nil? || local_env.nil?

    compare(env, chef_env, local_env)
  end
end

#show_error(msg, diff) ⇒ Object



96
97
98
99
# File 'lib/chef/knife/environment_sync.rb', line 96

def show_error(msg, diff)
  ui.info(msg + ui.color('difference(s) found', :yellow))
  pp(diff) if config[:diff]
end

#show_success(msg) ⇒ Object



92
93
94
# File 'lib/chef/knife/environment_sync.rb', line 92

def show_success(msg)
  ui.info(msg + ui.color('properly synchronized.', :green))
end