diff options
Diffstat (limited to 'lib/cpt-helpers')
-rw-r--r-- | lib/cpt-helpers | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/lib/cpt-helpers b/lib/cpt-helpers new file mode 100644 index 0000000..1589979 --- /dev/null +++ b/lib/cpt-helpers @@ -0,0 +1,77 @@ +# Helper functions to ensure portability and/or provide choices + +_seq() ( + # Pure shell counter meant to be used in 'for' loops. + i=0 buf='' + while [ "$(( i += 1 ))" -le "$1" ]; do + buf="$buf $i " + done + printf '%s' "$buf" +) + +_stat() ( + _user=; eval set -- "$(ls -ld "$1")" + id -u "${_user:=$3}" >/dev/null 2>&1 || _user=root + printf '%s' "$_user" +) + +sh256() { + # This is a sha256sum function for outputting a standard + # hash digest. sha256 on BSD systems require an '-r' flag + # for outputting the same way with sha256sum, and still, + # it outputs a single space between the hash and the file + # whereas sha256sum outputs double spaces. It fallbacks to + # openssl, but that is rarely ever needed. + { sha256sum "$1" 2>/dev/null || + sha256 -r "$1" 2>/dev/null || + openssl dgst -r -sha256 "$1" || + die "No sha256 program could be run." ;} | + + while read -r hash _; do printf '%s %s\n' "$hash" "$1"; done +} + +decompress() { + case $1 in + *.tar) cat ;; + *.bz2) bzip2 -cd ;; + *.xz|*.txz) xz -dcT 0 ;; + *.tgz|*.gz) gzip -cd ;; + *.zst) zstd -cd ;; + esac < "$1" +} + +as_root() { + # Simple function to run a command as root using either 'sudo', + # 'doas' or 'su'. Hurrah for choice. + [ "$uid" = 0 ] || log "Using '${su:-su}' (to become ${user:=root})" + + # We are exporting package manager variables, so that we still have the + # same repository paths / access to the same cache directories etc. + set -- HOME="$HOME" \ + USER="$user" \ + XDG_CACHE_HOME="$XDG_CACHE_HOME" \ + CPT_CACHE="$CPT_CACHE" \ + CPT_CHOICE="$CPT_CHOICE" \ + CPT_COMPRESS="$CPT_COMPRESS" \ + CPT_DEBUG="$CPT_DEBUG" \ + CPT_FETCH="$CPT_FETCH" \ + CPT_FORCE="$CPT_FORCE" \ + CPT_HOOK="$CPT_HOOK" \ + CPT_KEEPLOG="$CPT_KEEPLOG" \ + CPT_PATH="$CPT_PATH" \ + CPT_PID="$CPT_PID" \ + CPT_PROMPT="$CPT_PROMPT" \ + CPT_ROOT="$CPT_ROOT" \ + CPT_TMPDIR="$CPT_TMPDIR" \ + "$@" + + case ${su##*/} in + sls|sudo|doas) "$su" -u "$user" -- env "$@" ;; + su) su -c "env $* <&3" "$user" 3<&0 </dev/tty ;; + *) die "Invalid CPT_SU value: $su" ;; + esac +} + +# Local Variables: +# mode: sh +# End: |