From 81f9965b1688513ecb9d87814f31fc455dd24093 Mon Sep 17 00:00:00 2001 From: Hartley McGuire Date: Fri, 5 May 2023 14:33:05 -0400 Subject: [PATCH] Allow setting file permissions with create_file Previously, to restrict the permissions of a file created using create_file, chmod could be called right after. However, that leaves a short amount of time between when the file is first created and when the permissions are updated where another user could read the file. This commit enables passing file permissions to create_file so that permissions can be set when the file is created. --- lib/thor/actions/create_file.rb | 2 +- spec/actions/create_file_spec.rb | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/thor/actions/create_file.rb b/lib/thor/actions/create_file.rb index fa7b22cbb..4886dec6c 100644 --- a/lib/thor/actions/create_file.rb +++ b/lib/thor/actions/create_file.rb @@ -60,7 +60,7 @@ def invoke! invoke_with_conflict_check do require "fileutils" FileUtils.mkdir_p(File.dirname(destination)) - File.open(destination, "wb") { |f| f.write render } + File.open(destination, "wb", config[:perm]) { |f| f.write render } end given_destination end diff --git a/spec/actions/create_file_spec.rb b/spec/actions/create_file_spec.rb index 1e0c934e0..1eae4f1cc 100644 --- a/spec/actions/create_file_spec.rb +++ b/spec/actions/create_file_spec.rb @@ -33,6 +33,14 @@ def silence! expect(File.exist?(File.join(destination_root, "doc/config.rb"))).to be true end + it "allows setting file permissions" do + create_file("config/private.key", :perm => 0o600) + invoke! + + stat = File.stat(File.join(destination_root, "config/private.key")) + expect(stat.mode.to_s(8)).to eq "100600" + end + it "does not create a file if pretending" do create_file("doc/config.rb", {}, :pretend => true) invoke!