From 9765a4c0ff1c8399228d72b9c5d730bd323aa624 Mon Sep 17 00:00:00 2001 From: Achim Gsell Date: Wed, 10 Nov 2021 17:52:48 +0100 Subject: [PATCH] libstd.bash: std::split_path() added --- Pmodules/libstd.bash | 48 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/Pmodules/libstd.bash b/Pmodules/libstd.bash index 5161915..1684727 100644 --- a/Pmodules/libstd.bash +++ b/Pmodules/libstd.bash @@ -144,13 +144,38 @@ std::replace_path () { } # -# split an absolute path +# Functions to split a path into its components. # # Args: # $1 upvar -# $2 absolute path +# $2 absolute or relative path (depends on the function) # $3 opt upvar: number of components # +# Notes: +# std::split_path() +# if the path is absolute, the first element of the returned array is empty. +# +# std::split_abspath() +# the path must begin with a slash, otherwise std::die() is called with +# an internal error message. +# +# std::split_relpath() +# analog to std::split_abspath() with a relative path. +# +std::split_path() { + local parts="$1" + local -r path="$2" + + IFS='/' + local std__split_path_result=( ${std__split_path_tmp} ) + unset IFS + std::upvar ${parts} "${std__split_path_result[@]}" + if (( $# >= 3 )); then + # return number of parts + std::upvar "$3" ${#std__split_path_result[@]} + fi +} + std::split_abspath() { local parts="$1" local -r path="$2" @@ -170,6 +195,25 @@ std::split_abspath() { fi } +std::split_relpath() { + local parts="$1" + local -r path="$2" + if [[ "${path:0:1}" == '/' ]]; then + std::die 255 "Oops: Internal error in '${FUNCNAME[0]}' called by '${FUNCNAME[1]}' }" + else + local -r std__split_path_tmp="${path}" + fi + + IFS='/' + local std__split_path_result=( ${std__split_path_tmp} ) + unset IFS + std::upvar ${parts} "${std__split_path_result[@]}" + if (( $# >= 3 )); then + # return number of parts + std::upvar "$3" ${#std__split_path_result[@]} + fi +} + std::read_versions() { local -r fname="$1" local varname=''