deno_std icon indicating copy to clipboard operation
deno_std copied to clipboard

Path: Should `normalize()` remove trailing slashes?

Open jespertheend opened this issue 1 year ago • 3 comments

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/[email protected]/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)

jespertheend avatar Jul 14 '22 14:07 jespertheend

How about using parse and comparing base and dir?

kt3k avatar Jul 26 '22 15:07 kt3k

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.

jespertheend avatar Jul 27 '22 17:07 jespertheend

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.

pting-me avatar Dec 26 '22 20:12 pting-me