normalize_path: Squash leading slashes even without allow_leading

This currently changes builtin realpath with the "-s" option:

    builtin realpath -s ///tmp

previously would print "///tmp", now it prints "/tmp".

The only thing "allow_leading_double_slashes" does is allow *two*
slashes.

This is important for `path match`, to be introduced in #8265.
This commit is contained in:
Fabian Homborg 2021-09-09 17:22:14 +02:00
parent 1ff6160058
commit a78d9d8e9a
2 changed files with 15 additions and 4 deletions

View File

@ -281,10 +281,12 @@ wcstring normalize_path(const wcstring &path, bool allow_leading_double_slashes)
}
}
wcstring result = join_strings(new_comps, sep);
// Prepend one or two leading slashes.
// Two slashes are preserved. Three+ slashes are collapsed to one. (!)
result.insert(0, allow_leading_double_slashes && leading_slashes > 2 ? 1 : leading_slashes,
sep);
// If we don't allow leading double slashes, collapse them to 1 if there are any.
int numslashes = leading_slashes > 0 ? 1 : 0;
// If we do, prepend one or two leading slashes.
// Yes, three+ slashes are collapsed to one. (!)
if (allow_leading_double_slashes && leading_slashes == 2) numslashes = 2;
result.insert(0, numslashes, sep);
// Ensure ./ normalizes to . and not empty.
if (result.empty()) result.push_back(L'.');
return result;

View File

@ -95,6 +95,15 @@ else
echo "failure nonexistent-file-relative-to-a-symlink: $real_path != $expected_real_path" >&2
end
# We remove leading slashes even with "-s".
# This is how GNU realpath -s behaves, and also e.g.
# how bash normalizes its $PWD.
builtin realpath -s ///bin
# CHECK: /bin
builtin realpath -s //bin
# CHECK: /bin
# A path with two symlinks, first to a directory, second to a file, is correctly resolved.
ln -fs fish $XDG_DATA_HOME/fish-symlink2
touch $XDG_DATA_HOME/fish/real_file