#Path Normalisation

6 messages · Page 1 of 1 (latest)

unborn wave
#

Does anyone have any suggestions to normalise paths?
For example, it'd turn runtime\tests\scripts\./t/m.js into runtime\tests\scripts\t\m.js.
Basically it resolves . and .. paths.

graceful vapor
unborn wave
#

This seems to work

pub(crate) fn normalise_path<P: AsRef<Path>>(path: P) -> PathBuf {
    let mut buf = PathBuf::new();
    let segments = path.as_ref().components();

    for segment in segments {
        match segment {
            Component::ParentDir => { buf.pop(); },
            Component::CurDir => {},
            segment => buf.push(segment)
        }
    }
    buf
}
tall jasper
#

A little warning: foo/../bar is not the same as bar, since foo can be a symlink in which case it would visit the parent directory of the folder foo links to

unborn wave
#

I know symlinks are an issue but for now, I'm going to ignore those