Crystal: File.basename should support '.*' suffix

Created on 11 Feb 2018  路  6Comments  路  Source: crystal-lang/crystal

After several cases of files loss it became evident to me that File.basename is not supporting '.*' suffix currently. Please, consider adding this feature, because:

  • It's handy.
  • Ruby-backgrounded newcomers could suffer the lack of it.

Possible implementation:

def self.basename(path, suffix) : String
  suffix.check_no_null_byte
  return basename(path, self.extname(path)) if suffix == ".*"
  basename(path).chomp(suffix)
end

Possible specs:

it "gets basename removing suffix" do
  File.basename("/foo/bar/baz.cr", ".*").should eq("baz")
  File.basename("/foo/bar/baz.tar.gz", ".*").should eq("baz.tar")
end

EDITED: Should act consistently with File.extname.

Most helpful comment

You mean,

File.basename should not support '.*' suffix and instead do something completely different for it

I don't feel the same way. The function then becomes a time bomb when used with a variable 2nd argument.

All 6 comments

You mean,

File.basename should not support '.*' suffix and instead do something completely different for it

I don't feel the same way. The function then becomes a time bomb when used with a variable 2nd argument.

@oprypin I don't understand your comment. ".*" is a useful way to chop off any extension, and it being a time bomb doesn't make sense because Ruby has had it forever, and I don't recall anyone ever having problems with it.

Yeah but it's completely different behaviour. I'm not sure it makes sense to essentially support glob patterns in arbitrary path handling methods.

The same goal can actually be achieved with File.basename(file, File.extname(file)).

Maybe there could be a special method do access the name /wo extension directly. Python's pathlib for example has path.stem for this.

@straight-shoota
EDIT: Maybe you're right after all.

I'm actually surprised we don't have an existing way to get the filename without extension. Isn't this included in the new path PR?

Not yet. I only copied the existing basename methods for now. We'd have to find a name (just copy stem?) and decide what to do with basename(String) which essentially returns the basename without a specific extension.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

farleyknight picture farleyknight  路  64Comments

rdp picture rdp  路  112Comments

ezrast picture ezrast  路  84Comments

asterite picture asterite  路  78Comments

HCLarsen picture HCLarsen  路  162Comments