Skip to content

Commit

Permalink
Review fixes - guard FileUtils.rm_rf method call
Browse files Browse the repository at this point in the history
  • Loading branch information
zzaakiirr committed Oct 4, 2024
1 parent c051fd2 commit 1a87e3e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
10 changes: 9 additions & 1 deletion lib/command/terraform/generate.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ def generate_app_config(app)
def recreate_terraform_app_dir(app_path)
full_path = terraform_dir.join(app_path)

unless File.expand_path(full_path).include?(Cpflow.root_path.to_s)
Shell.abort("Directory to save terraform configuration files cannot be outside of current directory")
end

FileUtils.rm_rf(full_path)
FileUtils.mkdir_p(full_path)

Expand All @@ -80,7 +84,11 @@ def templates
def terraform_dir
@terraform_dir ||= begin
full_path = config.options.fetch(:dir, Cpflow.root_path.join("terraform"))
Pathname.new(full_path).tap { |path| FileUtils.mkdir_p(path) }
Pathname.new(full_path).tap do |path|
FileUtils.mkdir_p(path)
rescue StandardError => e
Shell.abort("Invalid directory: #{e.message}")
end
end
end
end
Expand Down
25 changes: 24 additions & 1 deletion spec/command/terraform/generate_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
TERRAFORM_CONFIG_DIR_PATH = GENERATOR_PLAYGROUND_PATH.join("terraform")

describe Command::Terraform::Generate do
subject(:result) { run_cpflow_command(described_class::SUBCOMMAND_NAME, described_class::NAME, "-a", app) }
subject(:result) { run_cpflow_command(described_class::SUBCOMMAND_NAME, described_class::NAME, *options) }

let!(:app) { dummy_test_app }
let(:options) { ["-a", app] }

before do
FileUtils.rm_rf(GENERATOR_PLAYGROUND_PATH)
Expand Down Expand Up @@ -67,6 +68,28 @@
end
end

context "when --dir option is outside of project dir" do
let(:options) { ["-a", app, "--dir", GEM_TEMP_PATH.join("path-outside-of-project").to_s] }

it "aborts command execution" do
expect(result[:status]).to eq(ExitCode::ERROR_DEFAULT)
expect(result[:stderr]).to include(
"Directory to save terraform configuration files cannot be outside of current directory"
)
end
end

context "when terraform config directory creation fails" do
before do
allow(FileUtils).to receive(:mkdir_p).and_raise("error")
end

it "aborts command execution" do
expect(result[:status]).to eq(ExitCode::ERROR_DEFAULT)
expect(result[:stderr]).to include("error")
end
end

def config_file_paths
common_config_files + app_config_files
end
Expand Down

0 comments on commit 1a87e3e

Please sign in to comment.