Skip to content

Fix File.join with empty path component #5915

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

Merged
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
5 changes: 5 additions & 0 deletions spec/std/file_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,11 @@ describe "File" do
File.join(["foo", "bar", "baz"]).should eq("foo/bar/baz")
File.join(["foo", "//bar//", "baz///"]).should eq("foo//bar//baz///")
File.join(["/foo/", "/bar/", "/baz/"]).should eq("/foo/bar/baz/")
File.join(["", "foo"]).should eq("foo")
File.join(["foo", ""]).should eq("foo/")
File.join(["", "", "foo"]).should eq("foo")
File.join(["foo", "", "bar"]).should eq("foo/bar")
File.join(["foo", "", "", "bar"]).should eq("foo/bar")
end

it "chown" do
Expand Down
6 changes: 5 additions & 1 deletion src/dir.cr
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,11 @@ class Dir
return 0 if Dir.exists?(path)

components = path.split(File::SEPARATOR)
if components.first == "." || components.first == ""
case components.first
when ""
components.shift
subpath = "/"
when "."
subpath = components.shift
else
subpath = "."
Expand Down
8 changes: 6 additions & 2 deletions src/file.cr
Original file line number Diff line number Diff line change
Expand Up @@ -707,15 +707,17 @@ class File < IO::FileDescriptor
# ```
def self.join(parts : Array | Tuple) : String
String.build do |str|
first = true
parts.each_with_index do |part, index|
part.check_no_null_byte
next if part.empty? && index != parts.size - 1

str << SEPARATOR if index > 0
str << SEPARATOR unless first

byte_start = 0
byte_count = part.bytesize

if index > 0 && part.starts_with?(SEPARATOR)
if !first && part.starts_with?(SEPARATOR)
byte_start += 1
byte_count -= 1
end
Expand All @@ -725,6 +727,8 @@ class File < IO::FileDescriptor
end

str.write part.unsafe_byte_slice(byte_start, byte_count)

first = false
end
end
end
Expand Down