modules/programs: sane-sandboxed: remove all forking from normPath

reduces time for librewolf benchmark from 90ms -> 65ms. there's still _some_ forking in this script, but it's constant now.
This commit is contained in:
Colin 2024-02-18 12:25:03 +00:00
parent f10f1ee7b1
commit fd6f8493a7

View File

@ -74,12 +74,14 @@ bwrapFlags=()
## UTILITIES/BOILERPLATE
# `normPath nameOfOutVar "$path"`
# remove duplicate //, reduce '.' and '..' (naively).
# expects a full path as input
# chomps trailing slashes.
# does not resolve symlinks, nor check for existence of any component of the path.
normPath() {
_npUnparsed="$1"
_npOut="$1"
_npUnparsed="$2"
_npComps=()
while [ -n "$_npUnparsed" ]; do
# chomp leading `/`
@ -102,18 +104,18 @@ normPath() {
done
# join the components
_npOut=
for _npComp in "${_npComps[@]}"; do
_npOut="$_npOut/$_npComp"
done
if [ -z "$_npOut" ]; then
echo "/"
if [ ${#_npComps[@]} -eq 0 ]; then
declare -g "$_npOut"="/"
else
echo "$_npOut"
_npJoined=
for _npComp in "${_npComps[@]}"; do
_npJoined="$_npJoined/$_npComp"
done
declare -g "$_npOut"="$_npJoined"
fi
}
# normPath() {
# normPathBashBuiltin() {
# # normPath implementation optimized by using bash builtins (`help realpath`):
# # -s: canonicalize `.` and `..` without resolving symlinks
# # -c: enforce that each component exist (intentionally omitted)
@ -123,17 +125,18 @@ normPath() {
# legacy coreutils normPath: definitive, but slow (requires a fork/exec subshell).
# bash `normPath` aims to be equivalent to this one.
# normPath() {
# normPathCoreutils() {
# # `man realpath`:
# # --logical: resolve `..` before dereferencing symlinks
# # --no-symlinks: don't follow symlinks
# # --canonicalize-missing: don't error if path components don't exist
# normPathOut="$(realpath --logical --no-symlinks --canonicalize-missing "$1")"
# realpath --logical --no-symlinks --canonicalize-missing "$1"
# }
# `parent nameOfOutVar "$path"`
# return the path to this file or directory's parent, even if the input doesn't exist.
parent() {
normPath "$1/.."
normPath "$1" "$2/.."
# normPath "$(dirname "$1")"
}
@ -203,7 +206,8 @@ tryPath() {
false
elif [ "$_how" = "parent" ]; then
# the caller wants access to the entire directory containing this directory regardless of the file's existence.
tryPath "$(parent "$_path")" "existing"
parent _tryPathParent "$_path"
tryPath "$_tryPathParent" "existing"
elif [ "$_how" = "existingFileOrParent" ]; then
# the caller wants access to the file, or write access to the directory so it may create the file if it doesn't exist.
tryPath "$_path" "existing" || tryPath "$_path" "parent"
@ -620,7 +624,8 @@ canonicalizePaths() {
# remove '//' and simplify '.', '..' paths, into canonical absolute logical paths.
_normPaths=()
for _path in "${paths[@]}"; do
_normPaths+=("$(normPath "$_path")")
normPath _canonPath "$_path"
_normPaths+=("$_canonPath")
done
# remove subpaths, but the result might include duplicates.