Skip to content

Instantly share code, notes, and snippets.

@ormaaj
Created Apr 26, 2022
Embed
What would you like to do?
#!/bin/ksh
typeset -T FileComparer=(
typeset src dst
typeset -a mv diff rm
compound _=(
_Bool unpackComplete=false
_Bool scanComplete=false
)
# Extract rar files under src
function unpack {
set -x
if (( _._.unpackComplete )); then
print -ru 2 'Already performed unpack. Aborting.'
return 1
fi
typeset x
for x in ~(N)*.rar; do
unrar e "$x" &&
rm -- "$x"
done
_._.unpackComplete=true
}
# Find identically named files with identical content in dst.
# Populates mv/diff/rm
function scan {
set -x
(( _._.unpackComplete )) || print -ru 2 'Warning: performing scan before unpack.'
if (( _._.scanComplete )); then
print -ru 2 'Warning: Scan performed once before - clearing previous results first.'
_.mv=() _.diff=() _.rm=()
fi
typeset x
for x in ~(N)"${_.src}"/!(*.rar); do
if [[ -e ${_.dst}/${x##*/} ]]; then
if cmp -s -- "$x" "${_.dst}/${x##*/}"; then
_.rm+=("$x")
else
_.diff+=("$x")
fi
else
_.mv+=("$x")
fi
done
_._.scanComplete=true
}
function commit {
set -x
typeset -p _._.scanComplete
if (( ! _._.scanComplete )); then
print -ru 2 'Must run scan prior to commit.'
return 1
fi
if [[ $1 != @(-n|--noprompt) ]]; then
typeset -p _.{rm,diff,mv} >&2
[[ -t 0 ]] || return
typeset confirm
IFS= read -rp 'Commit these changes? (`yes` to confirm.)' confirm
if [[ $confirm != ~(i)yes ]]; then
print -ru 2 'Aborting.'
return
fi
fi
set -x
#(( ${#_.mv[@]} > 0 )) && mv -i -- "${_.mv[@]}" "${_.dst}"
#(( ${#_.rm[@]} > 0 )) && rm -f -- "${rm[@]}"
print ok
set +x
}
)
function main {
set -x
typeset src=~ormaaj/doc/downloads/unsorted
typeset dst=~ormaaj/doc/text/not-piracy/unsorted
[[ -d $src && -d $dst ]] || return
[[ $1 == all ]] && set unpack scan commit
FileComparer comparison=(src=$src; dst=$dst)
typeset opt
for opt; do
case $opt in
unpack) comparison.unpack ;;
scan) comparison.scan ;;
commit) comparison.commit ;;
*) printf 'Invalid option: %s\n' "$opt" >&2
return 1
esac || return
done
}
main "$@"
# vim: set fenc=utf-8 ff=unix ft=sh ts=4 noet :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment