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

Handle File.extname edge case #6234

Merged
merged 7 commits into from
Jun 25, 2018
Merged
Changes from 3 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
22 changes: 12 additions & 10 deletions src/file.cr
Original file line number Diff line number Diff line change
Expand Up @@ -282,35 +282,37 @@ class File < IO::FileDescriptor
def self.extname(filename) : String
filename.check_no_null_byte

reader = Char::Reader.new(at_end: filename)
bytes = filename.to_slice
Copy link
Member

Choose a reason for hiding this comment

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

return "" if bytes.empty?

Copy link
Member

Choose a reason for hiding this comment

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

(and add a test for File.extname(""), which should be raising now)

current = bytes.size - 1

# if the pattern is foo. it has no extension
return "" if reader.current_char == '.'
return "" if bytes[current] == '.'.ord

# position the reader at the last . or SEPARATOR
while (current_char = reader.current_char) &&
(current_char != SEPARATOR && current_char != '.') &&
reader.has_previous?
reader.previous_char
# that is not the first char
while bytes[current] != SEPARATOR.ord &&
bytes[current] != '.'.ord &&
current > 0
current -= 1
end

# if we are the beginning of the string there is no extension
# /foo or .foo have no extension
return "" unless reader.has_previous?
return "" unless current > 0

# otherwise we are not at the beginning, and there is a previous char.
# if current is '/', then the pattern is prefix/foo and has no extension
return "" if current_char == SEPARATOR
return "" if bytes[current] == SEPARATOR.ord

# otherwise the current_char is '.'
# if previous is '/', then the pattern is prefix/.foo and has no extension
return "" if reader.previous_char == SEPARATOR
return "" if bytes[current - 1] == SEPARATOR.ord

# So the current char is '.',
# we are not at the beginning,
# the previous char is not a '/',
# and we have an extension
return filename.byte_slice(reader.pos + 1)
String.new(bytes[current, bytes.size - current])
end

# Converts *path* to an absolute path. Relative paths are
Expand Down