Skip to content

Commit

Permalink
Merge pull request #2388 from herwinw/io_write_perm
Browse files Browse the repository at this point in the history
Add :perm keyword argument to IO.write
  • Loading branch information
herwinw committed Dec 14, 2024
2 parents 0d1aa05 + b196c7d commit 4c9fd18
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
6 changes: 2 additions & 4 deletions spec/core/io/write_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -199,10 +199,8 @@

it "writes the file with the permissions in the :perm parameter" do
rm_r @filename
NATFIXME 'Add keyword arguments to IO.write', exception: ArgumentError, message: 'unknown keyword: :perm' do
IO.write(@filename, 'write :perm spec', mode: "w", perm: 0o755).should == 16
(File.stat(@filename).mode & 0o777) == 0o755
end
IO.write(@filename, 'write :perm spec', mode: "w", perm: 0o755).should == 16
(File.stat(@filename).mode & 0o777) == 0o755
end

it "writes binary data if no encoding is given" do
Expand Down
10 changes: 9 additions & 1 deletion src/io_object.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -306,11 +306,14 @@ Value IoObject::write_file(Env *env, Args &&args) {
auto string = args.at(1);
auto offset = args.at(2, nullptr);
auto mode = Value::integer(O_WRONLY | O_CREAT | O_CLOEXEC);
Value perm = nullptr;

if (!offset || offset->is_nil())
mode = Value::integer(IntegerObject::convert_to_nat_int_t(env, mode) | O_TRUNC);
if (kwargs && kwargs->has_key(env, "mode"_s))
mode = kwargs->delete_key(env, "mode"_s, nullptr);
if (kwargs && kwargs->has_key(env, "perm"_s))
perm = kwargs->delete_key(env, "perm"_s, nullptr);
if (filename->is_string() && filename->as_string()->string()[0] == '|')
env->raise("NotImplementedError", "no support for pipe in IO.write");

Expand All @@ -323,7 +326,12 @@ Value IoObject::write_file(Env *env, Args &&args) {
auto open_args_has_kw = next_args->last()->is_hash();
file = _new(env, File, Args(next_args, open_args_has_kw), nullptr)->as_file();
} else {
file = _new(env, File, Args({ filename, mode, kwargs }, true), nullptr)->as_file();
auto next_args = new ArrayObject { filename, mode };
if (perm)
next_args->push(perm);
if (kwargs)
next_args->push(kwargs);
file = _new(env, File, Args(next_args, kwargs != nullptr), nullptr)->as_file();
}
if (offset && !offset->is_nil())
file->set_pos(env, offset);
Expand Down

0 comments on commit 4c9fd18

Please sign in to comment.