Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add File#rename #13640

Merged
merged 1 commit into from
Jul 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions spec/std/file_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,16 @@ describe "File" do
end
end
end

it "renames a File instance" do
with_tempfile("rename-source.txt", "rename-target.txt") do |source_path, target_path|
f = File.new(source_path, "w")
f.rename target_path
f.path.should eq target_path
File.exists?(source_path).should be_false
File.exists?(target_path).should be_true
end
end
end

# There are more detailed specs for `Path#expand` in path_spec.cr
Expand Down
6 changes: 6 additions & 0 deletions src/file.cr
Original file line number Diff line number Diff line change
Expand Up @@ -866,6 +866,12 @@ class File < IO::FileDescriptor
end
end

# Rename the current `File`
def rename(new_filename : Path | String) : Nil
File.rename(@path, new_filename)
@path = new_filename.to_s
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do the both cases the same?
new_filename could be just a file name (as the test covers)) but could be a (full) path...
BTW is @path a (stringified) path or a file name?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@path is whatever you pass to the constructor. It can be a single file name or consist of multiple path components. It makes no difference which.

end

# Sets the access and modification times of *filename*.
#
# Use `#utime` if the `File` is already open.
Expand Down