1 Commits

5 changed files with 71 additions and 307 deletions

120
build.sh
View File

@@ -1,8 +1,23 @@
#!/usr/bin/env bash
build::addLicense() {
local target="${1:?}"
local licenseText="#
build::rdlink() {
readonly build_dir="$(cd "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
readonly rdlinkRelease="${build_dir}/release/rdlink.sh"
readonly color_green='\033[1;32m'
readonly color_red='\033[1;31m'
readonly color_less='\033[0m'
readonly shellcheck_cmd="$(command -v shellcheck)"
readonly fileHeader="#!/usr/bin/env bash
# rdlink [OPTIONS] <PATH>
# [OPTION]
# -- : End of options marker
# -* : Other options are ignored
#
# Version: $(git describe --long --tags --always --dirty)
# Author: Martin Winkler
# Origin: https://winklerfamilie.eu/git/efelon/rdlink.git
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
@@ -17,118 +32,51 @@ build::addLicense() {
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"
printf '%s' "${licenseText}" >> "${target}"
}
build::headerRdlink() {
local target="${1:?}"
local fileHeader="#!/usr/bin/env bash
# rdlink.sh [OPTIONS] <PATH>
# [OPTION]
# -- : End of options marker
# -* : Other options are ignored
#
# Version: $(git describe --long --tags --always --dirty)
# Author: Martin Winkler
# Origin: https://winklerfamilie.eu/git/efelon/rdlink.git
"
printf '%s' "${fileHeader}" > "${target}"
build::addLicense "${target}"
}
build::headerStarter() {
local target="${1:?}"
local fileHeader="#!/usr/bin/env bash
# starter.sh
#
# Start or source your application at the end to have the
# environment variable \$_origin available.
#
# Version: $(git describe --long --tags --always --dirty)
# Author: Martin Winkler
# Origin: https://winklerfamilie.eu/git/efelon/rdlink.git
"
printf '%s' "${fileHeader}" > "${target}"
build::addLicense "${target}"
}
build::rdlink() {
readonly build_dir="$(cd "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
readonly rdlinkRelease="${build_dir}/release/rdlink.sh"
readonly starterRelease="${build_dir}/release/starter.sh"
readonly color_green='\033[1;32m'
readonly color_red='\033[1;31m'
readonly color_less='\033[0m'
readonly shellcheck_cmd="$(command -v shellcheck)"
local testresult_graphic=
testresult_graphic="${color_green}${color_less}" # alt. symbol ✓
testresult_graphic_fail="${color_red}${color_less}" # alt. symbol ≠
if ! mkdir -p "$(dirname -- "${rdlinkRelease}")" ; then
printf ' [ERROR] Cannot create release directory\n'
printf " [ERROR] Cannot create release directory\n"
return 1
fi
printf '# Building releases based on rdlink.sh\n'
printf "# Building rdlink release\n"
build::headerRdlink "${rdlinkRelease}"
printf ' (Extracting script part and removing debug information)\n'
printf ' Building release/rdlink.sh...'
# Write header
printf "%s" "${fileHeader}" > "${rdlinkRelease}"
printf " Extracting script part and removing debug information..."
# Get essential script content
# * extract script part
# * remove script marker
# * remove debug function calls
# * remove debug options from rdlink
# * replace multiple empty lines with one
#if cat "${build_dir}/rdlink.sh" \
# | sed -n '/### Script.*/,/### Script EOF/ p' \
# | sed '/### Script.*/d; /^[[:blank:]]*info/d; /-d\{1,2\}/,/;;/d' \
# | sed '/^$/N; /^\n$/D' \
# >> "${rdlinkRelease}" 2>/dev/null ; then
if sed -n '/### Script.*/,/### Script EOF/ p' < "${build_dir}/rdlink.sh" \
| sed '/### Script.*/d; /^[[:blank:]]*info/d; /-d\{1,2\}/,/;;/d' \
| sed '/^$/N; /^\n$/D' \
>> "${rdlinkRelease}" 2>/dev/null ; then
printf '%b' "${testresult_graphic}\n"
printf "%b" "${testresult_graphic}\n"
else
printf '%b' "${testresult_graphic_fail}\n"
printf "%b" "${testresult_graphic_fail}\n"
return 1
fi
{
build::headerStarter "${starterRelease}"
printf ' Building release/starter.sh...'
if sed -n '/### Script.*/,/### Script Starter EOF/ p' < "${build_dir}/rdlink.sh" \
| sed '/### Script.*/d; /^[[:blank:]]*info/d; /-d\{1,2\}/,/;;/d' \
| sed '/^$/N; /^\n$/D' \
>> "${starterRelease}" 2>/dev/null ; then
printf '%b' "${testresult_graphic}\n"
else
printf '%b' "${testresult_graphic_fail}\n"
return 1
fi
printf '_origin="$(cd "$(dirname -- "$(rl::rdlink "${BASH_SOURCE[0]}")")" >/dev/null 2>&1 && pwd)"\n' >> "${starterRelease}"
printf 'export _origin\n\n' >> "${starterRelease}"
printf '# Uncomment one of the next lines and replace "tostart.sh" with your script\n' >> "${starterRelease}"
printf '# to have _origin available even on platforms not supporting readlink -f.\n\n' >> "${starterRelease}"
printf '#bash "${_origin}/tostart.sh"\n' >> "${starterRelease}"
printf '#. "${_origin}/tostart.sh"\n' >> "${starterRelease}"
printf '#"${_origin}/tostart.sh"\n' >> "${starterRelease}"
}
if [[ "${shellcheck_cmd}" ]] ; then
printf '%b\n' " Running shellcheck for rdlink...\033[1A\033[s\n"
printf "%b\n" " Running shellcheck...\033[1A\033[s\n"
if "${shellcheck_cmd}" "${rdlinkRelease}" ; then
printf '%b' "\033[u${testresult_graphic}\n"
else
return 1
fi
printf '%b\n' " Running shellcheck for starter...\033[1A\033[s\n"
if "${shellcheck_cmd}" "${starterRelease}" ; then
printf '%b' "\033[u${testresult_graphic}\n"
printf "%b" "\033[u${testresult_graphic}\n"
else
return 1
fi
fi
chmod +x "${rdlinkRelease}"
return 0
}

171
rdlink.sh
View File

@@ -24,7 +24,7 @@ function rl::log () {
local log_line=""
while IFS=$'\n' read -r log_line; do
printf '%s [%9s] %s\n' "$(date -u +"%Y-%m-%d %H:%M:%S UTC")" "${log_level}" "${log_line}" 1>&2
printf "%s [%9s] %s\n" "$(date -u +"%Y-%m-%d %H:%M:%S UTC")" "${log_level}" "${log_line}" 1>&2
done <<< "${@:-}"
}
emergency() { rl::log emergency "${@}"; exit 1; }
@@ -39,69 +39,26 @@ msg() { echo "$@"; true; }
### Script
rl::rdlink() {
local subject="${1:-}"
local work=
local subject=
info "Processing: ${subject}"
info " with pwd: $(pwd)"
# Remove multiple /
while [[ "${subject:-}" = *"//"* ]]; do
subject="${subject/\/\///}"
done
# Follow multiple symlinks
while subject="$(rl::quicklink "${subject}")" ; do
: # A link was resolved at least once
info " rl::rdlink - Link found: $subject"
done
# Special cases handling
{
# If subject is still a link, after rl::quicklink call(s)
# current user has no permission to access the link itself
# (e.g. /proc/**/cwd)
if [ -L "${subject}" ] ; then
info " rl::rdlink exit - can't access link ${subject}"
printf '\n'
return 1
fi
}
# Empty output if (dirname $subject) is not a valid path
if ! work="$(rl::canon "${subject}")" ; then
info " rl::rdlink exit - invalid path ${work}"
printf '\n'
return 1
else
subject="${work}"
fi
printf '%s\n' "${subject}"
subject="${1:-}"
while [[ "${subject:-}" = *"//"* ]]; do subject="${subject/\/\///}"; done
while subject="$(rl::quicklink "${subject}")" ; do : ; done
[ -L "${subject}" ] && printf "\n" && return 1
subject="$(rl::canon "${subject}")" || { printf "\n"; return 1; }
printf "%s\n" "${subject}"
}
rl::quicklink() {
subject=
work=
local subject=
local work=
info "Quicklink... ${1:-}"
# Check if current candidate is a symlink
if ! subject=$(readlink -- "${1:-}"); then
printf -- '%s\n' "${1:-}"
return 1
fi
info " rl::quicklink symlink ${1} -> ${subject}"
# relative symlink target; prepend its parent direcotry
subject=$(readlink -- "${1:-}") || { printf -- "%s\n" "${1:-}"; return 1; }
if [[ "${subject}" != "/"* ]]; then
work="$(rl::canon "$(dirname -- "${1:-}")")"
subject="${work}/${subject}"
info " rl::quicklink relative link resolved: ${subject}"
fi
printf '%s\n' "${subject}"
return 0
printf "%s\n" "${subject}"
}
rl::canon() {
@@ -113,120 +70,52 @@ rl::canon() {
local retval=0
start="${1:-}"
info "Canonicalize path... ${start}"
while (( run )) ; do
if work="$(cd "${start}" >/dev/null 2>&1 && pwd -P)" ; then
# Special: `pwd -P` returns with // as root for links starting at /
# e.g. $(readlink /proc/self/root) == "/"
# $(cd /proc/self/root/mnt && pwd -P) == "//mnt"
subject="$(rl::normalize "${work}")"
info " rl::canon valid directory: ${subject}"
run=0
subject="$(rl::normalize "${work}")"; run=0
elif work="$(cd "$(dirname -- "${start}")" >/dev/null 2>&1 && pwd -P)" ; then
bname="$(basename -- "${start}")"
# Special: / produces //
[[ "${work}" = "/" ]] && work=
[[ "${work}" == "/" ]] && work=
subject="${work}${bname:+"/${bname}"}"
info " rl::canon valid parent: ${subject}"
# Special: Succeed with valid element after second run; see special below
# e.g. /root/.
# * /root is valid but not accessible
if (( retval )) && [ -e "${subject}" ] ;then
info " rl::canon valid element"
retval=0
fi
run=0
(( retval )) && [ -e "${subject}" ] && retval=0; run=0
else
# Special: Some paths may be resolvable after normalization
# e.g. somedir/..
# * base "somedir" does not exist
# * but irrelevant because of /..
# * resolves to pwd but fails by readlink -f
work="$(rl::normalize "${start}")"
if [[ "${work}" != "${start}" ]] ; then
info " rl::canon retry with: ${work}"
start="${work}"
retval=1
continue
fi
info " rl::canon invalid path: ${work}"
subject="${work}"
run=0 && retval=1
[[ "${work}" != "${start}" ]] && start="${work}" && retval=1 && continue
subject="${work}"; run=0 && retval=1
fi
done
printf -- '%s\n' "${subject}"
return ${retval}
printf -- "%s\n" "${subject}"; return ${retval}
}
rl::normalize() {
local work=
info "Normalizing path... ${1:-}"
work="${1:-}"
# Remove dir/.. sequences.
local rex_tmp='[^/][^/]*/\.\./*'
while [[ "${work}" =~ $rex_tmp ]] ; do
work="${work/"${BASH_REMATCH[0]}"/}"
done
# Remove /./ and /.$ sequences.
rex_tmp='/\.(/|$)'
while [[ "$work" =~ $rex_tmp ]]; do
work="${work/${BASH_REMATCH[0]}/${BASH_REMATCH[1]/$//}}"
done
# Remove leading ./
while [[ "${work}" =~ [^/][^/]*/\.\./* ]] ; do work="${work/"${BASH_REMATCH[0]}"/}"; done
while [[ "$work" =~ /\.(/|$) ]]; do work="${work/${BASH_REMATCH[0]}/${BASH_REMATCH[1]/$//}}"; done
work="${work#./*}"
# Remove trailing /
rex_tmp='(.*[^/])/$'
if [[ "${work}" =~ $rex_tmp ]] ; then
work="${BASH_REMATCH[1]}"
fi
info " rl::normalize result: ${work}"
printf -- '%s\n' "${work}"
[[ "${work}" =~ (.*[^/])/$ ]] && work="${BASH_REMATCH[1]}"
printf -- "%s\n" "${work}"
}
### Script Starter EOF
rl::main() {
local file=
local arg=
for arg in "$@"; do
case "$arg" in
--)
shift
break ;;
-d|--debug)
shift
LOG_LEVEL=7 ;;
-dd)
shift
set -o xtrace ;;
-*)
shift ;;
--) shift; break ;;
-d|--debug) shift; LOG_LEVEL=7 ;;
-dd) shift; set -o xtrace ;;
-*) shift ;;
esac
done
info "BASH rdlink"
for file in "$@"; do
rl::rdlink "$file"
done
for file in "$@"; do rl::rdlink "$file"; done
}
# Provide as function to be called when sourced
rdlink() {
rl::main "$@"
}
rdlink() { rl::main "$@"; }
### Check if script is _sourced
### https://stackoverflow.com/a/28776166
@@ -244,9 +133,7 @@ else # All other shells: examine $0 for known shell binary filenames
fi
###
if (( ! _sourced )); then
rl::main "$@"
fi
(( ! _sourced )) && rl::main "$@"
### Script EOF

View File

@@ -1,17 +1,17 @@
#!/usr/bin/env bash
readonly getenv_dir="$(cd "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
get_os_version() {
readonly getenv_dir="$(cd "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
local utils_version=
local os_version=
local utils_version=
os_version="$(bash "${getenv_dir}/distro.sh" | sed 's/ /_/g; s/\//-/g')"
os_version="$(bash "${getenv_dir}/distro.sh" | sed 's/ /_/g')"
bash_version="$(bash --version | sed -n '/bash, [Vv]ersion/p' | sed 's/.*[Vv]ersion \([0-9.]\+\).*/\1/g')"
if utils_version="$(readlink --version 2>&1 | grep "BusyBox")" ; then
if utils_version="$(readlink --version 2>&1 | grep -E "BusyBox")" ; then
utils_version="$(sed 's/\(BusyBox v[0-9\.]\+\).*/\1/g' <<<${utils_version})"
elif utils_version="$(readlink --version 2>&1 | grep "GNU core")" ; then
elif utils_version="$(readlink --version 2>&1 | grep -E "GNU core")" ; then
utils_version="$(sed 's/.*\(GNU [[:alnum:]]\+\). \([0-9\.]\+\).*/\1 \2/g' <<<${utils_version})"
else
utils_version="utils_unkown"
@@ -19,7 +19,7 @@ get_os_version() {
# Replace " " with _
utils_version="${utils_version// /_}"
echo "${os_version:-"$(uname -s)"}_${bash_version:+bash_${bash_version}}_${utils_version}"
echo "${os_version}_${bash_version:+bash_${bash_version}}_${utils_version}"
}
get_os_version

View File

@@ -230,7 +230,7 @@ rl::testcmp() {
local testresult_graphic="${color_red}${color_less}" # alt. symbol ≠
local link="$(readlink -- "${input}")"
if [[ "${actual}" =~ ${expect} ]] ; then
if [[ "${expect}" == "${actual}" ]] ; then
# Don't print success for this flag
(( flag_printerror )) && return 0
testresult=1

View File

@@ -132,44 +132,12 @@ _ta_tmp="${test_dir:-"/tmp"}/tmp_assert"
# [1] input == [2] expected
# [3] input == [4] expected
# ...
assert_canonicalize=( "Canonicalize invalid path"
"///tmp//./b" "/tmp/b"
"//tmp//./b/.." ""
"//tmp//./b/." ""
"//tmp//./b/" "/tmp/b"
"///notthere//...../help/." ""
)
toassert_init() {
{
# Base directory for the test initialization
mkdir -p "${_ta_tmp}"
cd "${_ta_tmp}"
# assert_no_permission
mkdir -p "nopermdir"
chmod 400 "nopermdir"
ln -s "nopermdir" "nopermdirl"
ln -s "/" "lroot"
ln -s "/root" "lroothome"
# assert_links
touch "a"
ln -s "a" "a 2"
ln -s "a 2" "a 3"
mkdir -p "dir_1"
mkdir -p "dir_2/dir_22"
touch "dir_2/dir_22/file"
ln -s "dir_2/dir_22" "dir_3_l"
ln -s "../dir_3_l/file" "dir_1/file"
# assert_relative
ln -s "../nofile" "nofile_l"
ln -s "../nodir/nofile" "nopath_l"
}
# Base directory for the test
cd "${_ta_tmp}"
@@ -182,41 +150,6 @@ toassert_init() {
"${_ta_tmp}/miss c" "${_ta_tmp}/miss c"
"rel_a" "${_ta_tmp}/rel_a"
"../rel_b" "$(cd ".." && pwd)/rel_b"
"-v" "$PWD/-v" # Not recommended file naming
"../-v" "$(cd "$PWD/.." && pwd)/-v" # Not recommended file naming
"-v/.." "" # Not recommended file naming
)
assert_relative=( "Resolving of relative links"
# Invalid
"nofile_l" "$(cd "$PWD/.." && pwd)/nofile"
"nopath_l" ""
# Valid
"dir_1/file" "$PWD/dir_2/dir_22/file" # Valid relative link to path with relative element
)
assert_no_permission=( "No permission to enter directory (direct and link)"
"nopermdir" "$PWD/nopermdir"
"nopermdirl" "$PWD/nopermdir"
"lroot" "/"
"lroothome" "/root"
"/" "/"
"/root" "/root"
"/root/" "/root"
"/root/." "/root"
"/root/.." "/"
)
assert_links=( "Test - Valid links"
"${_ta_tmp}/a 3" "$PWD/a" # slink chain a3 -> a2 -> a
"${_ta_tmp}/a" "$PWD/a"
"${_ta_tmp}/a 2" "$PWD/a"
"/dev/stdin" "/dev/pts/[0-9]+"
#"/dev/stdout" "" # skip - Always different ( add for assert )
#"/dev/fd" # Test skip - /dev/fd is different on every call
#"/etc/mtab" # skip - Always different
#"/proc/mounts" # skip - Always different
#"/proc/net/"* # skip - Always different
)
assert_force_fail=( "Force fail"
@@ -225,11 +158,7 @@ toassert_init() {
# Add test arrays to global test array from test_rdlink
toassert+=(
assert_canonicalize
assert_relative
assert_no_permission
assert_invalid_files
assert_links
#assert_force_fail
)
}