universalarchive.plugin.zsh 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. function ua() {
  2. local usage=\
  3. "Archive files and directories using a given compression algorithm.
  4. Usage: $0 <format> <files>
  5. Example: $0 tbz PKGBUILD
  6. Supported archive formats are:
  7. 7z, bz2, gz, lzma, lzo, rar, tar, tbz (tar.bz2), tgz (tar.gz),
  8. tlz (tar.lzma), txz (tar.xz), tZ (tar.Z), xz, Z, zip, and zst."
  9. if [[ $# -lt 2 ]]; then
  10. print -u2 -- "$usage"
  11. return 1
  12. fi
  13. local ext="$1"
  14. local input="${2:a}"
  15. shift
  16. if [[ ! -e "$input" ]]; then
  17. print -u2 -- "$input not found"
  18. return 1
  19. fi
  20. # generate output file name
  21. local output
  22. if [[ $# -gt 1 ]]; then
  23. output="${input:h:t}"
  24. elif [[ -f "$input" ]]; then
  25. output="${input:r:t}"
  26. elif [[ -d "$input" ]]; then
  27. output="${input:t}"
  28. fi
  29. # if output file exists, generate a random name
  30. if [[ -f "${output}.${ext}" ]]; then
  31. output=$(mktemp "${output}_XXX") && rm "$output" || return 1
  32. fi
  33. # add extension
  34. output="${output}.${ext}"
  35. # safety check
  36. if [[ -f "$output" ]]; then
  37. print -u2 -- "output file '$output' already exists. Aborting"
  38. return 1
  39. fi
  40. case "$ext" in
  41. 7z) 7z u "${output}" "${@}" ;;
  42. bz2) bzip2 -vcf "${@}" > "${output}" ;;
  43. gz) gzip -vcf "${@}" > "${output}" ;;
  44. lzma) lzma -vc -T0 "${@}" > "${output}" ;;
  45. lzo) lzop -vc "${@}" > "${output}" ;;
  46. rar) rar a "${output}" "${@}" ;;
  47. tar) tar -cvf "${output}" "${@}" ;;
  48. tbz|tar.bz2) tar -cvjf "${output}" "${@}" ;;
  49. tgz|tar.gz) tar -cvzf "${output}" "${@}" ;;
  50. tlz|tar.lzma) XZ_OPT=-T0 tar --lzma -cvf "${output}" "${@}" ;;
  51. txz|tar.xz) XZ_OPT=-T0 tar -cvJf "${output}" "${@}" ;;
  52. tZ|tar.Z) tar -cvZf "${output}" "${@}" ;;
  53. xz) xz -vc -T0 "${@}" > "${output}" ;;
  54. Z) compress -vcf "${@}" > "${output}" ;;
  55. zip) zip -rull "${output}" "${@}" ;;
  56. zst) zstd -c -T0 "${@}" > "${output}" ;;
  57. *) print -u2 -- "$usage"; return 1 ;;
  58. esac
  59. }