Skip to content

Suggest handling case insensitivity on .ends_with(".ext") #6425

Closed
@kangalio

Description

@kangalio

What it does

When .ends_with() is called on a String or &str, and the parameter looks like a file extension (regex \.([a-z0-9]{1,5})|([A-Z0-9]{1,5})), inform the programmer that this code will not handle differently-cased filenames well - potentially a bug. Additionally, a correct replacement is suggested (see below).

Categories

  • Kind: clippy::pedantic or perhaps clippy::correctness

What is the advantage of the recommended code over the original code

It handles file extensions correctly regardless of case. In Windows, this behavior is very much expected since the entire operating system has case-insensitive filenames. In Linux, filenames are usually case-sensitive, but I think even on Linux, it's standard behavior to recognize file extensions regardless of case.

Drawbacks

  • The suggested improvement is harder to read than the naive case-sensitive version
  • The line .ends_with(".ext") might not be a file extension check at all. It could mean something else for which case-sensitivity makes sense

Example

if !filename.ends_with(".abc") {
    panic!("Please provide an ABC file");
}

Could be written as:

if filename.rsplit('.').next().map(|ext| ext.eq_ignore_ascii_case("abc")) != Some(true) {
    panic!("Please provide an ABC file");
}

Or like this (nightly-only because of Path::eq_ignore_ascii_case):

let filename = Path::new(filename);
if filename.extension().map(|ext| ext.eq_ignore_ascii_case("abc")) != Some(true) {
    panic!("Please provide an ABC file");
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsL-suggestionLint: Improving, adding or fixing lint suggestionsgood first issueThese issues are a good way to get started with Clippy

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions