summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordanielsdeleo <dan@getchef.com>2014-09-02 11:48:13 -0700
committerdanielsdeleo <dan@getchef.com>2014-09-03 12:44:46 -0700
commiteffa8c560eef788d679f8af55f3af6eefaf619da (patch)
treed5344d88f3249b1e10e143c60c8d745091a5eaa2
parentd762b7ba7483378439737f14b9b8b3b1a9cb727e (diff)
downloadchef-effa8c560eef788d679f8af55f3af6eefaf619da.tar.gz
Extract Knife config file find/load to a reusable component
-rw-r--r--lib/chef/application/client.rb11
-rw-r--r--lib/chef/knife.rb145
-rw-r--r--lib/chef/workstation_config_loader.rb156
-rw-r--r--spec/integration/client/client_spec.rb12
-rw-r--r--spec/unit/knife/config_file_selection_spec.rb135
-rw-r--r--spec/unit/knife_spec.rb33
-rw-r--r--spec/unit/workstation_config_loader_spec.rb231
7 files changed, 426 insertions, 297 deletions
diff --git a/lib/chef/application/client.rb b/lib/chef/application/client.rb
index c581bb0da0..1dc29db307 100644
--- a/lib/chef/application/client.rb
+++ b/lib/chef/application/client.rb
@@ -24,6 +24,7 @@ require 'chef/daemon'
require 'chef/log'
require 'chef/config_fetcher'
require 'chef/handler/error_report'
+require 'chef/workstation_config_loader'
class Chef::Application::Client < Chef::Application
@@ -223,6 +224,11 @@ class Chef::Application::Client < Chef::Application
:long => "--config-file-jail PATH",
:description => "Directory under which config files are allowed to be loaded (no client.rb or knife.rb outside this path will be loaded)."
+ option :dont_load_config,
+ :long => "--dont-load-config",
+ :description => "Refuse to load a config file and use defaults. This is for development and not a stable API",
+ :boolean => true
+
option :run_lock_timeout,
:long => "--run-lock-timeout SECONDS",
:description => "Set maximum duration to wait for another client run to finish, default is indefinitely.",
@@ -274,10 +280,9 @@ class Chef::Application::Client < Chef::Application
def load_config_file
Chef::Config.config_file_jail = config[:config_file_jail] if config[:config_file_jail]
- if !config.has_key?(:config_file)
+ if !config.has_key?(:config_file) && !config[:dont_load_config]
if config[:local_mode]
- require 'chef/knife'
- config[:config_file] = Chef::Knife.locate_config_file
+ config[:config_file] = Chef::WorkstationConfigLoader.new(nil).config_location
else
config[:config_file] = Chef::Config.platform_specific_path("/etc/chef/client.rb")
end
diff --git a/lib/chef/knife.rb b/lib/chef/knife.rb
index 038ab61715..9a68da8982 100644
--- a/lib/chef/knife.rb
+++ b/lib/chef/knife.rb
@@ -20,7 +20,7 @@
require 'forwardable'
require 'chef/version'
require 'mixlib/cli'
-require 'chef/config_fetcher'
+require 'chef/workstation_config_loader'
require 'chef/mixin/convert_to_class_name'
require 'chef/mixin/path_sanity'
require 'chef/knife/core/subcommand_loader'
@@ -159,6 +159,27 @@ class Chef
end
end
+ # Shared with subclasses
+ @@chef_config_dir = nil
+
+ def self.load_config(explicit_config_file)
+ config_loader = WorkstationConfigLoader.new(explicit_config_file)
+ Chef::Log.debug("Using configuration from #{config_loader.config_location}")
+ config_loader.load
+
+ ui.warn("No knife configuration file found") if config_loader.no_config_found?
+ @@chef_config_dir = config_loader.chef_config_dir
+
+ config_loader
+ rescue Exceptions::ConfigurationError => e
+ ui.error(ui.color("CONFIGURATION ERROR:", :red) + e.message)
+ exit 1
+ end
+
+ def self.chef_config_dir
+ @@chef_config_dir
+ end
+
# Run knife for the given +args+ (ARGV), adding +options+ to the list of
# CLI options that the subcommand knows how to handle.
# ===Arguments
@@ -239,40 +260,12 @@ class Chef
exit 10
end
- def self.working_directory
- a = if Chef::Platform.windows?
- ENV['CD']
- else
- ENV['PWD']
- end || Dir.pwd
-
- a
- end
-
def self.reset_config_path!
@@chef_config_dir = nil
end
reset_config_path!
-
- # search upward from current_dir until .chef directory is found
- def self.chef_config_dir
- if @@chef_config_dir.nil? # share this with subclasses
- @@chef_config_dir = false
- full_path = working_directory.split(File::SEPARATOR)
- (full_path.length - 1).downto(0) do |i|
- candidate_directory = File.join(full_path[0..i] + [".chef" ])
- if File.exist?(candidate_directory) && File.directory?(candidate_directory)
- @@chef_config_dir = candidate_directory
- break
- end
- end
- end
- @@chef_config_dir
- end
-
-
public
# Create a new instance of the current class configured for the given
@@ -322,39 +315,6 @@ class Chef
config_file_settings
end
- def self.config_fetcher(candidate_config)
- Chef::ConfigFetcher.new(candidate_config, Chef::Config.config_file_jail)
- end
-
- def self.locate_config_file
- candidate_configs = []
-
- # Look for $KNIFE_HOME/knife.rb (allow multiple knives config on same machine)
- if ENV['KNIFE_HOME']
- candidate_configs << File.join(ENV['KNIFE_HOME'], 'knife.rb')
- end
- # Look for $PWD/knife.rb
- if Dir.pwd
- candidate_configs << File.join(Dir.pwd, 'knife.rb')
- end
- # Look for $UPWARD/.chef/knife.rb
- if chef_config_dir
- candidate_configs << File.join(chef_config_dir, 'knife.rb')
- end
- # Look for $HOME/.chef/knife.rb
- if ENV['HOME']
- candidate_configs << File.join(ENV['HOME'], '.chef', 'knife.rb')
- end
-
- candidate_configs.each do | candidate_config |
- fetcher = config_fetcher(candidate_config)
- if !fetcher.config_missing?
- return candidate_config
- end
- end
- return nil
- end
-
# Apply Config in this order:
# defaults from mixlib-cli
# settings from config file, via Chef::Config[:knife]
@@ -416,70 +376,13 @@ class Chef
end
def configure_chef
- if !config[:config_file]
- located_config_file = self.class.locate_config_file
- config[:config_file] = located_config_file if located_config_file
- end
-
- # Don't try to load a knife.rb if it wasn't specified.
- if config[:config_file]
- Chef::Config.config_file = config[:config_file]
- fetcher = Chef::ConfigFetcher.new(config[:config_file], Chef::Config.config_file_jail)
- if fetcher.config_missing?
- ui.error("Specified config file #{config[:config_file]} does not exist#{Chef::Config.config_file_jail ? " or is not under config file jail #{Chef::Config.config_file_jail}" : ""}!")
- exit 1
- end
- Chef::Log.debug("Using configuration from #{config[:config_file]}")
- read_config(fetcher.read_config, config[:config_file])
- else
- # ...but do log a message if no config was found.
- Chef::Config[:color] = config[:color]
- ui.warn("No knife configuration file found")
- end
+ config_loader = self.class.load_config(config[:config_file])
+ config[:config_file] = config_loader.config_location
merge_configs
apply_computed_config
end
- def read_config(config_content, config_file_path)
- Chef::Config.from_string(config_content, config_file_path)
- rescue SyntaxError => e
- ui.error "You have invalid ruby syntax in your config file #{config_file_path}"
- ui.info(ui.color(e.message, :red))
- if file_line = e.message[/#{Regexp.escape(config_file_path)}:[\d]+/]
- line = file_line[/:([\d]+)$/, 1].to_i
- highlight_config_error(config_file_path, line)
- end
- exit 1
- rescue Exception => e
- ui.error "You have an error in your config file #{config_file_path}"
- ui.info "#{e.class.name}: #{e.message}"
- filtered_trace = e.backtrace.grep(/#{Regexp.escape(config_file_path)}/)
- filtered_trace.each {|line| ui.msg(" " + ui.color(line, :red))}
- if !filtered_trace.empty?
- line_nr = filtered_trace.first[/#{Regexp.escape(config_file_path)}:([\d]+)/, 1]
- highlight_config_error(config_file_path, line_nr.to_i)
- end
-
- exit 1
- end
-
- def highlight_config_error(file, line)
- config_file_lines = []
- IO.readlines(file).each_with_index {|l, i| config_file_lines << "#{(i + 1).to_s.rjust(3)}: #{l.chomp}"}
- if line == 1
- lines = config_file_lines[0..3]
- lines[0] = ui.color(lines[0], :red)
- else
- lines = config_file_lines[Range.new(line - 2, line)]
- lines[1] = ui.color(lines[1], :red)
- end
- ui.msg ""
- ui.msg ui.color(" # #{file}", :white)
- lines.each {|l| ui.msg(l)}
- ui.msg ""
- end
-
def show_usage
stdout.puts("USAGE: " + self.opt_parser.to_s)
end
diff --git a/lib/chef/workstation_config_loader.rb b/lib/chef/workstation_config_loader.rb
new file mode 100644
index 0000000000..faf7bd0cd1
--- /dev/null
+++ b/lib/chef/workstation_config_loader.rb
@@ -0,0 +1,156 @@
+#
+# Author:: Daniel DeLeo (<dan@getchef.com>)
+# Copyright:: Copyright (c) 2014 Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require 'chef/config_fetcher'
+require 'chef/config'
+
+class Chef
+
+ class WorkstationConfigLoader
+
+ # Path to a config file requested by user, (e.g., via command line option). Can be nil
+ attr_reader :explicit_config_file
+
+ def initialize(explicit_config_file)
+ @explicit_config_file = explicit_config_file
+ @config_location = nil
+ end
+
+ def no_config_found?
+ config_location.nil?
+ end
+
+ def config_location
+ @config_location ||= (explicit_config_file || locate_local_config)
+ end
+
+ def chef_config_dir
+ if @chef_config_dir.nil?
+ @chef_config_dir = false
+ full_path = working_directory.split(File::SEPARATOR)
+ (full_path.length - 1).downto(0) do |i|
+ candidate_directory = File.join(full_path[0..i] + [".chef" ])
+ if File.exist?(candidate_directory) && File.directory?(candidate_directory)
+ @chef_config_dir = candidate_directory
+ break
+ end
+ end
+ end
+ @chef_config_dir
+ end
+
+ def load
+ # Ignore it if there's no explicit_config_file and can't find one at a
+ # default path.
+ return false if config_location.nil?
+
+ if explicit_config_file && !path_exists?(config_location)
+ raise Exceptions::ConfigurationError, "Specified config file #{config_location} does not exist"
+ end
+
+ # Have to set Chef::Config.config_file b/c other config is derived from it.
+ Chef::Config.config_file = config_location
+ read_config(IO.read(config_location), config_location)
+ end
+
+ # (Private API, public for test purposes)
+ def env
+ ENV
+ end
+
+ # (Private API, public for test purposes)
+ def path_exists?(path)
+ Pathname.new(path).expand_path.exist?
+ end
+
+ private
+
+ def locate_local_config
+ candidate_configs = []
+
+ # Look for $KNIFE_HOME/knife.rb (allow multiple knives config on same machine)
+ if env['KNIFE_HOME']
+ candidate_configs << File.join(env['KNIFE_HOME'], 'knife.rb')
+ end
+ # Look for $PWD/knife.rb
+ if Dir.pwd
+ candidate_configs << File.join(Dir.pwd, 'knife.rb')
+ end
+ # Look for $UPWARD/.chef/knife.rb
+ if chef_config_dir
+ candidate_configs << File.join(chef_config_dir, 'knife.rb')
+ end
+ # Look for $HOME/.chef/knife.rb
+ if env['HOME']
+ candidate_configs << File.join(env['HOME'], '.chef', 'knife.rb')
+ end
+
+ candidate_configs.find do | candidate_config |
+ path_exists?(candidate_config)
+ end
+ end
+
+ def working_directory
+ a = if Chef::Platform.windows?
+ env['CD']
+ else
+ env['PWD']
+ end || Dir.pwd
+
+ a
+ end
+
+ def read_config(config_content, config_file_path)
+ Chef::Config.from_string(config_content, config_file_path)
+ rescue SignalException
+ raise
+ rescue SyntaxError => e
+ message = ""
+ message << "You have invalid ruby syntax in your config file #{config_file_path}\n\n"
+ message << "#{e.class.name}: #{e.message}\n"
+ if file_line = e.message[/#{Regexp.escape(config_file_path)}:[\d]+/]
+ line = file_line[/:([\d]+)$/, 1].to_i
+ message << highlight_config_error(config_file_path, line)
+ end
+ raise Exceptions::ConfigurationError, message
+ rescue Exception => e
+ message = "You have an error in your config file #{config_file_path}\n\n"
+ message << "#{e.class.name}: #{e.message}\n"
+ filtered_trace = e.backtrace.grep(/#{Regexp.escape(config_file_path)}/)
+ filtered_trace.each {|bt_line| message << " " << bt_line << "\n" }
+ if !filtered_trace.empty?
+ line_nr = filtered_trace.first[/#{Regexp.escape(config_file_path)}:([\d]+)/, 1]
+ message << highlight_config_error(config_file_path, line_nr.to_i)
+ end
+ raise Exceptions::ConfigurationError, message
+ end
+
+
+ def highlight_config_error(file, line)
+ config_file_lines = []
+ IO.readlines(file).each_with_index {|l, i| config_file_lines << "#{(i + 1).to_s.rjust(3)}: #{l.chomp}"}
+ if line == 1
+ lines = config_file_lines[0..3]
+ else
+ lines = config_file_lines[Range.new(line - 2, line)]
+ end
+ "Relevant file content:\n" + lines.join("\n") + "\n"
+ end
+
+ end
+end
diff --git a/spec/integration/client/client_spec.rb b/spec/integration/client/client_spec.rb
index f0d978c516..f896512aed 100644
--- a/spec/integration/client/client_spec.rb
+++ b/spec/integration/client/client_spec.rb
@@ -33,17 +33,17 @@ EOM
context 'and no config file' do
it 'should complete with success when cwd is just above cookbooks and paths are not specified' do
- result = shell_out("#{chef_client} -z -o 'x::default' --config-file-jail \"#{path_to('')}\"", :cwd => path_to(''))
+ result = shell_out("#{chef_client} -z -o 'x::default' --dont-load-config", :cwd => path_to(''))
result.error!
end
it 'should complete with success when cwd is below cookbooks and paths are not specified' do
- result = shell_out("#{chef_client} -z -o 'x::default' --config-file-jail \"#{path_to('')}\"", :cwd => path_to('cookbooks/x'))
+ result = shell_out("#{chef_client} -z -o 'x::default' --dont-load-config", :cwd => path_to('cookbooks/x'))
result.error!
end
it 'should fail when cwd is below high above and paths are not specified' do
- result = shell_out("#{chef_client} -z -o 'x::default' --config-file-jail \"#{path_to('')}\"", :cwd => File.expand_path('..', path_to('')))
+ result = shell_out("#{chef_client} -z -o 'x::default' --dont-load-config", :cwd => File.expand_path('..', path_to('')))
result.exitstatus.should == 1
end
end
@@ -52,15 +52,11 @@ EOM
before { file '.chef/knife.rb', 'xxx.xxx' }
it 'should load .chef/knife.rb when -z is specified' do
- result = shell_out("#{chef_client} -z -o 'x::default' --config-file-jail \"#{path_to('')}\"", :cwd => path_to(''))
+ result = shell_out("#{chef_client} -z -o 'x::default'", :cwd => path_to(''))
# FATAL: Configuration error NoMethodError: undefined method `xxx' for nil:NilClass
result.stdout.should include("xxx")
end
- it 'fails to load .chef/knife.rb when -z is specified and --config-file-jail does not include the .chef/knife.rb' do
- result = shell_out("#{chef_client} -z -o 'x::default' --config-file-jail \"#{path_to('roles')}\"", :cwd => path_to(''))
- result.error!
- end
end
it "should complete with success" do
diff --git a/spec/unit/knife/config_file_selection_spec.rb b/spec/unit/knife/config_file_selection_spec.rb
deleted file mode 100644
index 0a623714d7..0000000000
--- a/spec/unit/knife/config_file_selection_spec.rb
+++ /dev/null
@@ -1,135 +0,0 @@
-#
-# Author:: Nicolas Vinot (<aeris@imirhil.fr>)
-# Copyright:: Copyright (c) 2010 Opscode, Inc.
-# License:: Apache License, Version 2.0
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
-require 'tmpdir'
-
-describe Chef::Knife do
-
- let(:missing_config_fetcher) do
- double(Chef::ConfigFetcher, :config_missing? => true)
- end
-
- let(:available_config_fetcher) do
- double(Chef::ConfigFetcher, :config_missing? => false,
- :read_config => "")
- end
-
- def have_config_file(path)
- Chef::ConfigFetcher.should_receive(:new).at_least(1).times.with(path, nil).and_return(available_config_fetcher)
- end
-
- before do
- # Make sure tests can run when HOME is not set...
- @original_home = ENV["HOME"]
- ENV["HOME"] = Dir.tmpdir
- end
-
- after do
- ENV["HOME"] = @original_home
- end
-
- before :each do
- Chef::Config.stub(:from_file).and_return(true)
- Chef::ConfigFetcher.stub(:new).and_return(missing_config_fetcher)
- end
-
- it "configure knife from KNIFE_HOME env variable" do
- env_config = File.expand_path(File.join(Dir.tmpdir, 'knife.rb'))
- have_config_file(env_config)
-
- ENV['KNIFE_HOME'] = Dir.tmpdir
- @knife = Chef::Knife.new
- @knife.configure_chef
- @knife.config[:config_file].should == env_config
- end
-
- it "configure knife from PWD" do
- pwd_config = "#{Dir.pwd}/knife.rb"
- have_config_file(pwd_config)
-
- @knife = Chef::Knife.new
- @knife.configure_chef
- @knife.config[:config_file].should == pwd_config
- end
-
- it "configure knife from UPWARD" do
- upward_dir = File.expand_path "#{Dir.pwd}/.chef"
- upward_config = File.expand_path "#{upward_dir}/knife.rb"
- have_config_file(upward_config)
- Chef::Knife.stub(:chef_config_dir).and_return(upward_dir)
-
- @knife = Chef::Knife.new
- @knife.configure_chef
- @knife.config[:config_file].should == upward_config
- end
-
- it "configure knife from HOME" do
- home_config = File.expand_path(File.join("#{ENV['HOME']}", "/.chef/knife.rb"))
- have_config_file(home_config)
-
- @knife = Chef::Knife.new
- @knife.configure_chef
- @knife.config[:config_file].should == home_config
- end
-
- it "configure knife from nothing" do
- ::File.stub(:exist?).and_return(false)
- @knife = Chef::Knife.new
- @knife.ui.should_receive(:warn).with("No knife configuration file found")
- @knife.configure_chef
- @knife.config[:config_file].should be_nil
- end
-
- it "configure knife precedence" do
- env_config = File.join(Dir.tmpdir, 'knife.rb')
- pwd_config = "#{Dir.pwd}/knife.rb"
- upward_dir = File.expand_path "#{Dir.pwd}/.chef"
- upward_config = File.expand_path "#{upward_dir}/knife.rb"
- home_config = File.expand_path(File.join("#{ENV['HOME']}", "/.chef/knife.rb"))
- configs = [ env_config, pwd_config, upward_config, home_config ]
-
- Chef::Knife.stub(:chef_config_dir).and_return(upward_dir)
- ENV['KNIFE_HOME'] = Dir.tmpdir
-
- @knife = Chef::Knife.new
-
- @knife.configure_chef
- @knife.config[:config_file].should be_nil
-
- have_config_file(home_config)
- @knife = Chef::Knife.new
- @knife.configure_chef
- @knife.config[:config_file].should == home_config
-
- have_config_file(upward_config)
- @knife = Chef::Knife.new
- @knife.configure_chef
- @knife.config[:config_file].should == upward_config
-
- have_config_file(pwd_config)
- @knife = Chef::Knife.new
- @knife.configure_chef
- @knife.config[:config_file].should == pwd_config
-
- have_config_file(env_config)
- @knife = Chef::Knife.new
- @knife.configure_chef
- @knife.config[:config_file].should == env_config
- end
-end
diff --git a/spec/unit/knife_spec.rb b/spec/unit/knife_spec.rb
index 70b60a2f96..2db6b40b28 100644
--- a/spec/unit/knife_spec.rb
+++ b/spec/unit/knife_spec.rb
@@ -44,34 +44,6 @@ describe Chef::Knife do
@stderr = StringIO.new
end
- describe "selecting a config file" do
- context "when the current working dir is inside a symlinked directory" do
- before do
- Chef::Knife.reset_config_path!
- # pwd according to your shell is /home/someuser/prod/chef-repo, but
- # chef-repo is a symlink to /home/someuser/codes/chef-repo
- if Chef::Platform.windows?
- ENV.should_receive(:[]).with("CD").and_return("/home/someuser/prod/chef-repo")
- else
- ENV.should_receive(:[]).with("PWD").and_return("/home/someuser/prod/chef-repo")
- end
-
- Dir.stub(:pwd).and_return("/home/someuser/codes/chef-repo")
- end
-
- after do
- Chef::Knife.reset_config_path!
- end
-
- it "loads the config from the non-dereferenced directory path" do
- File.should_receive(:exist?).with("/home/someuser/prod/chef-repo/.chef").and_return(false)
- File.should_receive(:exist?).with("/home/someuser/prod/.chef").and_return(true)
- File.should_receive(:directory?).with("/home/someuser/prod/.chef").and_return(true)
- Chef::Knife.chef_config_dir.should == "/home/someuser/prod/.chef"
- end
- end
- end
-
describe "after loading a subcommand" do
before do
Chef::Knife.reset_subcommands!
@@ -247,7 +219,7 @@ describe Chef::Knife do
end
it "loads lazy dependencies" do
- command = Chef::Knife.run(%w{test yourself})
+ Chef::Knife.run(%w{test yourself})
KnifeSpecs::TestYourself.test_deps_loaded.should be_true
end
@@ -256,7 +228,8 @@ describe Chef::Knife do
KnifeSpecs::TestYourself.class_eval do
deps { other_deps_loaded = true }
end
- command = Chef::Knife.run(%w{test yourself})
+
+ Chef::Knife.run(%w{test yourself})
KnifeSpecs::TestYourself.test_deps_loaded.should be_true
other_deps_loaded.should be_true
end
diff --git a/spec/unit/workstation_config_loader_spec.rb b/spec/unit/workstation_config_loader_spec.rb
new file mode 100644
index 0000000000..aa49e6ff04
--- /dev/null
+++ b/spec/unit/workstation_config_loader_spec.rb
@@ -0,0 +1,231 @@
+#
+# Author:: Daniel DeLeo (<dan@getchef.com>)
+# Copyright:: Copyright (c) 2014 Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require 'spec_helper'
+require 'tempfile'
+require 'chef/workstation_config_loader'
+
+describe Chef::WorkstationConfigLoader do
+
+ let(:explicit_config_location) { nil }
+
+ let(:env) { {} }
+
+ let(:config_loader) do
+ described_class.new(explicit_config_location).tap do |c|
+ allow(c).to receive(:env).and_return(env)
+ end
+ end
+
+ # Test methods that do I/O or reference external state which are stubbed out
+ # elsewhere.
+ describe "external dependencies" do
+ let(:config_loader) { described_class.new(nil) }
+
+ it "delegates to ENV for env" do
+ expect(config_loader.env).to equal(ENV)
+ end
+
+ it "tests a path's existence" do
+ expect(config_loader.path_exists?('/nope/nope/nope/nope/frab/jab/nab')).to be(false)
+ expect(config_loader.path_exists?(__FILE__)).to be(true)
+ end
+
+ end
+
+ describe "locating the config file" do
+ context "without an explicit config" do
+
+ before do
+ allow(config_loader).to receive(:path_exists?).with(an_instance_of(String)).and_return(false)
+ end
+
+ it "has no config if HOME is not set" do
+ expect(config_loader.config_location).to be(nil)
+ expect(config_loader.no_config_found?).to be(true)
+ end
+
+ context "when HOME is set and contains a knife.rb" do
+
+ let(:home) { "/Users/example.user" }
+
+ before do
+ env["HOME"] = home
+ allow(config_loader).to receive(:path_exists?).with("#{home}/.chef/knife.rb").and_return(true)
+ end
+
+ it "uses the config in HOME/.chef/knife.rb" do
+ expect(config_loader.config_location).to eq("#{home}/.chef/knife.rb")
+ end
+
+ context "and/or a parent dir contains a .chef dir" do
+
+ let(:env_pwd) { "/path/to/cwd" }
+
+ before do
+ env["PWD"] = env_pwd
+ allow(config_loader).to receive(:path_exists?).with("#{env_pwd}/.chef/knife.rb").and_return(true)
+ allow(File).to receive(:exist?).with("#{env_pwd}/.chef").and_return(true)
+ allow(File).to receive(:directory?).with("#{env_pwd}/.chef").and_return(true)
+ end
+
+ it "prefers the config from parent_dir/.chef" do
+ expect(config_loader.config_location).to eq("#{env_pwd}/.chef/knife.rb")
+ end
+
+ context "and/or the current working directory contains a .chef dir" do
+
+ let(:cwd) { Dir.pwd }
+
+ before do
+ allow(config_loader).to receive(:path_exists?).with("#{cwd}/knife.rb").and_return(true)
+ end
+
+ it "prefers a config located in the cwd" do
+ expect(config_loader.config_location).to eq("#{cwd}/knife.rb")
+ end
+
+
+ context "and/or KNIFE_HOME is set" do
+
+ let(:knife_home) { "/path/to/knife/home" }
+
+ before do
+ env["KNIFE_HOME"] = knife_home
+ allow(config_loader).to receive(:path_exists?).with("#{knife_home}/knife.rb").and_return(true)
+ end
+
+ it "prefers a config located in KNIFE_HOME" do
+ expect(config_loader.config_location).to eq("/path/to/knife/home/knife.rb")
+ end
+
+ end
+ end
+ end
+ end
+
+ context "when the current working dir is inside a symlinked directory" do
+ before do
+ # pwd according to your shell is /home/someuser/prod/chef-repo, but
+ # chef-repo is a symlink to /home/someuser/codes/chef-repo
+ env["CD"] = "/home/someuser/prod/chef-repo" # windows
+ env["PWD"] = "/home/someuser/prod/chef-repo" # unix
+
+ Dir.stub(:pwd).and_return("/home/someuser/codes/chef-repo")
+ end
+
+ it "loads the config from the non-dereferenced directory path" do
+ expect(File).to receive(:exist?).with("/home/someuser/prod/chef-repo/.chef").and_return(false)
+ expect(File).to receive(:exist?).with("/home/someuser/prod/.chef").and_return(true)
+ expect(File).to receive(:directory?).with("/home/someuser/prod/.chef").and_return(true)
+
+ expect(config_loader).to receive(:path_exists?).with("/home/someuser/prod/.chef/knife.rb").and_return(true)
+
+ expect(config_loader.config_location).to eq("/home/someuser/prod/.chef/knife.rb")
+ end
+ end
+ end
+
+ context "when given an explicit config to load" do
+
+ let(:explicit_config_location) { "/path/to/explicit/config.rb" }
+
+ it "prefers the explicit config" do
+ expect(config_loader.config_location).to eq(explicit_config_location)
+ end
+
+ end
+ end
+
+
+ describe "loading the config file" do
+
+ context "when no explicit config is specifed and no implicit config is found" do
+
+ before do
+ allow(config_loader).to receive(:path_exists?).with(an_instance_of(String)).and_return(false)
+ end
+
+ it "skips loading" do
+ expect(config_loader.config_location).to be(nil)
+ expect(config_loader.load).to be(false)
+ end
+
+ end
+
+ context "when an explict config is given but it doesn't exist" do
+
+ let(:explicit_config_location) { "/nope/nope/nope/frab/jab/nab" }
+
+ it "raises a configuration error" do
+ expect { config_loader.load }.to raise_error(Chef::Exceptions::ConfigurationError)
+ end
+
+ end
+
+ context "when the config file exists" do
+
+ let(:config_content) { "" }
+
+ let(:explicit_config_location) do
+ t = Tempfile.new("#{described_class}-rspec-test")
+ t.print(config_content)
+ t.close
+ t.path
+ end
+
+ after { File.unlink(explicit_config_location) }
+
+ context "and is valid" do
+
+ let(:config_content) { "config_file_evaluated(true)" }
+
+ it "loads the config" do
+ expect(config_loader.load).to be(true)
+ expect(Chef::Config.config_file_evaluated).to be(true)
+ end
+
+ it "sets Chef::Config.config_file" do
+ config_loader.load
+ expect(Chef::Config.config_file).to eq(explicit_config_location)
+ end
+ end
+
+ context "and has a syntax error" do
+
+ let(:config_content) { "{{{{{:{{" }
+
+ it "raises a ConfigurationError" do
+ expect { config_loader.load }.to raise_error(Chef::Exceptions::ConfigurationError)
+ end
+ end
+
+ context "and raises a ruby exception during evaluation" do
+
+ let(:config_content) { ":foo\n:bar\nraise 'oops'\n:baz\n" }
+
+ it "raises a ConfigurationError" do
+ expect { config_loader.load }.to raise_error(Chef::Exceptions::ConfigurationError)
+ end
+ end
+
+ end
+
+ end
+
+end