gen-downloadlist-entry (1998B)
1 #!/bin/zsh 2 setopt no_unset warn_create_global 3 zmodload zsh/stat || exit $? 4 5 typeset -g basedir=${0:P:h:h} 6 7 typeset -g hl_fatal hl_reset 8 if (( $terminfo[colors] >= 8 )); then 9 hl_fatal='%F{red}%B'; hl_fatal=${(%)hl_fatal} 10 hl_warn='%F{yellow}%B'; hl_warn=${(%)hl_warn} 11 hl_reset='%b%f'; hl_reset=${(%)hl_reset} 12 fi 13 14 # helper that prints out stack, error message and exits 15 die_ret() { 16 set +x 17 local ret n 18 ret=$1 19 shift 20 print -r - >&2 "${hl_fatal}Fatal$hl_reset error occurend in:" 21 for n in {${#funcfiletrace}..1}; do 22 printf >&2 '%d> %s (%s)\n' $n "$funcfiletrace[$n]" "$functrace[$n]" 23 done 24 printf >&2 '%s\n' "${hl_fatal}*$hl_reset $^@" 25 exit $ret 26 } 27 28 die() { 29 set +x 30 die_ret 1 "$@" 31 } 32 die100() { # 100: wrong usage 33 set +x 34 die_ret 100 "$@" 35 } 36 die111() { # 111: system call failed 37 set +x 38 die_ret 111 "$@" 39 } 40 41 -() { # Run command and die on nonzero exitcode 42 "$@" || die_ret $? "command failed with exitcode $?: ${(j: :)${(q)@}}" 43 } 44 45 in() { # Run command in subdirectory and die on nonzero exitcode 46 local d=$1 47 shift 48 (cd $d && "$@") || die_ret $? "command failed with exitcode $? (dir=${(qqq)d}): ${(j: :)${(q)@}}" 49 } 50 51 pretend() { 52 : "$@" 53 } 54 typeset -f -t pretend 55 56 confirm() { 57 local REPLY 58 printf >&2 '%s ' ${1:-y/N} 59 if read -q; then 60 echo 61 else 62 echo 63 exit 1 64 fi 65 } 66 67 ### Main {{{1 68 69 main() { 70 local digest url fname dl_dir dl_list 71 local -A statinfo 72 73 url=$1 74 fname=${2:-./${1:t}} 75 dl_dir=$basedir/cache/downloads/sha256 76 dl_list=$basedir/downloadlist.sha256 77 78 [[ -f $dl_list ]] || 79 die100 "Could not find downloadlist file, expected ${(qqq)dl_list}" 80 81 [[ -d $dl_dir ]] || 82 die100 "Could not find downloads directory, expected ${(qqq)dl_dir}" 83 84 zstat -H statinfo - $fname || die_ret $? "stat failed" 85 digest=${"$(sha256sum $fname)"%% *} || die_ret $? "sha256sum failed" 86 printf '%s %s %s\n' $digest $statinfo[size] $url 87 confirm "Write to $dl_list and move file to downloads? [y/N]" 88 printf >>$dl_list '%s %s %s\n' $digest $statinfo[size] $url 89 mv -v $fname $dl_dir/$digest 90 } 91 92 main "$@"