ajout abspath

This commit is contained in:
Jephté Clain 2023-11-08 16:08:12 +04:00
parent af332ea961
commit 633b554547
1 changed files with 76 additions and 0 deletions

View File

@ -155,3 +155,79 @@ function ac_set_tmpdir() {
_setv "$1" "$sr__t" _setv "$1" "$sr__t"
fi fi
} }
################################################################################
## manipulation de chemins
#XXX repris tel quel depuis nutools, à migrer
function normpath() {
# normaliser le chemin $1, qui est soit absolu, soit relatif à $2 (qui vaut
# $(pwd) par défaut)
local -a parts
local part ap
IFS=/ read -a parts <<<"$1"
if [ "${1#/}" != "$1" ]; then
ap=/
elif [ -n "$2" ]; then
ap="$2"
else
ap="$(pwd)"
fi
for part in "${parts[@]}"; do
if [ "$part" == "." ]; then
continue
elif [ "$part" == ".." ]; then
ap="${ap%/*}"
[ -n "$ap" ] || ap=/
else
[ "$ap" != "/" ] && ap="$ap/"
ap="$ap$part"
fi
done
recho "$ap"
}
function __normpath() {
# normaliser dans les cas simple le chemin absolu $1. sinon retourner 1.
# cette fonction est utilisée par abspath()
if [ -d "$1" ]; then
if [ -x "$1" ]; then
# le cas le plus simple: un répertoire dans lequel on peut entrer
(cd "$1"; pwd)
return 0
fi
elif [ -f "$1" ]; then
local dn="$(dirname -- "$1")" bn="$(basename -- "$1")"
if [ -x "$dn" ]; then
# autre cas simple: un fichier situé dans un répertoire dans lequel
# on peut entrer
(cd "$dn"; echo "$(pwd)/$bn")
return 0
fi
fi
return 1
}
function abspath() {
# Retourner un chemin absolu vers $1. Si $2 est non nul et si $1 est un chemin
# relatif, alors $1 est exprimé par rapport à $2, sinon il est exprimé par
# rapport au répertoire courant.
# Si le chemin n'existe pas, il n'est PAS normalisé. Sinon, les meilleurs
# efforts sont faits pour normaliser le chemin.
local ap="$1"
if [ "${ap#/}" != "$ap" ]; then
# chemin absolu. on peut ignorer $2
__normpath "$ap" && return
else
# chemin relatif. il faut exprimer le chemin par rapport à $2
local cwd
if [ -n "$2" ]; then
cwd="$(abspath "$2")"
else
cwd="$(pwd)"
fi
ap="$cwd/$ap"
__normpath "$ap" && return
fi
# dans les cas spéciaux, il faut calculer "manuellement" le répertoire absolu
normpath "$ap"
}