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

Path: Should normalize() remove trailing slashes? #2441

Open
jespertheend opened this issue Jul 14, 2022 · 3 comments
Open

Path: Should normalize() remove trailing slashes? #2441

jespertheend opened this issue Jul 14, 2022 · 3 comments

Comments

@jespertheend
Copy link
Contributor

Is your feature request related to a problem? Please describe.

I'm trying to find out if a file is inside a specific directory. My plan was to do it like this:

import { common } from "https://deno.land/std@0.148.0/path/mod.ts";
function insideDir(file, dir) {
    const result = common([file, dir]);
    return result == dir;
}

However, this doesn't work if the dir argument doesn't contain a trailing slash. For example:

common(["/path/to/dir", "/path/to/dir/file.txt"]);

returns "/path/to/dir/", and "/path/to/dir/" != "/path/to/dir"

Describe the solution you'd like

If I'm not mistaken, /path/to/dir and /path/to/dir/ both point to the same thing. If so, then wouldn't it make sense to have a function that removes trailing slashes from paths? Maybe normalize() would be a good fit for this.

Describe alternatives you've considered

  • Add a function to std that performs this exact algorithm
  • Make common() remove the trailing slash
  • It seems resolve() also removes trailing slashes, though passing just a single command isn't really documented anywhere (and neither does it contain tests for this case)
@kt3k
Copy link
Member

kt3k commented Jul 26, 2022

How about using parse and comparing base and dir?

@jespertheend
Copy link
Contributor Author

That would work in a scenario where you'd want to see if a file is a direct child of a specific directory. But I'd also want to detect files in subdirectories. I.e.

insideDir("/path/to/dir/with/file.txt", "/path/to/dir/")

should also return true.

I'm currently wrapping the result of common() in a resolve() call, which seems to work. Though I have only tested this on macOS.

@pting-me
Copy link
Contributor

I agree. I think that resolve('/path/to/dir') and normalize('/path/to/dir') should produce the same output. Also think common should omit trailing slashes as well.

If you look at the Go std library Clean and Dir functions, they explicitly don't return trailing slashes unless it's a root directory. Dir is similar to common in that it still omits the trailing slash even though we know it will always return a directory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants