From 02d6cb5000231fdb65711701b8f2e338c3702fa9 Mon Sep 17 00:00:00 2001 From: Adam Borocz Date: Wed, 3 Apr 2013 13:34:03 +0100 Subject: [PATCH] Temporarily alter ENV['PWD'] while running commands This will help us make sure that both commands that use Dir#pwd, and the ones that use ENV['PWD'] will correctly execute inside the sandbox. --- lib/strainer/command.rb | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/strainer/command.rb b/lib/strainer/command.rb index 657cf96..98ced7f 100644 --- a/lib/strainer/command.rb +++ b/lib/strainer/command.rb @@ -36,8 +36,7 @@ def initialize(line, cookbook, options = {}) def run! title(label) - Strainer.ui.debug "Changing working directory to '#{Strainer.sandbox_path}'" - Dir.chdir Strainer.sandbox_path do + inside_sandbox do Strainer.ui.debug "Running '#{command}'" speak command PTY.spawn command do |r, _, pid| @@ -63,6 +62,23 @@ def run! end end + # Execute a block inside the sandbox directory defined in 'Strainer.sandbox_path'. + # This will first change the 'PWD' env variable to the sandbox path, and then + # pass the given block into 'Dir.chdir'. 'PWD' is restored to the original value + # when the block is finished. + # + # @yield The block to execute inside the sandbox + def inside_sandbox(&block) + Strainer.ui.debug "Changing working directory to '#{Strainer.sandbox_path}'" + original_pwd = ENV['PWD'] + + ENV['PWD'] = Strainer.sandbox_path.to_s + Dir.chdir(Strainer.sandbox_path, &block) + ENV['PWD'] = original_pwd + + Strainer.ui.debug "Restored working directory to '#{original_pwd}'" + end + # Have this command output text, prefixing with its output with the # command name #