urltools.plugin.zsh 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. # URL Tools
  2. # Adds handy command line aliases useful for dealing with URLs
  3. #
  4. # Taken from:
  5. # http://ruslanspivak.com/2010/06/02/urlencode-and-urldecode-from-a-command-line/
  6. if [[ $(whence $URLTOOLS_METHOD) = "" ]]; then
  7. URLTOOLS_METHOD=""
  8. fi
  9. if [[ $(whence node) != "" && ( "x$URLTOOLS_METHOD" = "x" || "x$URLTOOLS_METHOD" = "xnode" ) ]]; then
  10. alias urlencode='node -e "console.log(encodeURIComponent(process.argv[1]))"'
  11. alias urldecode='node -e "console.log(decodeURIComponent(process.argv[1]))"'
  12. elif [[ $(whence python) != "" && ( "x$URLTOOLS_METHOD" = "x" || "x$URLTOOLS_METHOD" = "xpython" ) ]]; then
  13. alias urlencode='python -c "import sys, urllib as ul; print ul.quote_plus(sys.argv[1])"'
  14. alias urldecode='python -c "import sys, urllib as ul; print ul.unquote_plus(sys.argv[1])"'
  15. elif [[ $(whence xxd) != "" && ( "x$URLTOOLS_METHOD" = "x" || "x$URLTOOLS_METHOD" = "xshell" ) ]]; then
  16. function urlencode() {echo $@ | tr -d "\n" | xxd -plain | sed "s/\(..\)/%\1/g"}
  17. function urldecode() {printf $(echo -n $@ | sed 's/\\/\\\\/g;s/\(%\)\([0-9a-fA-F][0-9a-fA-F]\)/\\x\2/g')"\n"}
  18. elif [[ $(whence ruby) != "" && ( "x$URLTOOLS_METHOD" = "x" || "x$URLTOOLS_METHOD" = "xruby" ) ]]; then
  19. alias urlencode='ruby -r cgi -e "puts CGI.escape(ARGV[0])"'
  20. alias urldecode='ruby -r cgi -e "puts CGI.unescape(ARGV[0])"'
  21. elif [[ $(whence php) != "" && ( "x$URLTOOLS_METHOD" = "x" || "x$URLTOOLS_METHOD" = "xphp" ) ]]; then
  22. alias urlencode='php -r "echo rawurlencode(\$argv[1]); echo \"\n\";"'
  23. alias urldecode='php -r "echo rawurldecode(\$argv[1]); echo \"\\n\";"'
  24. elif [[ $(whence perl) != "" && ( "x$URLTOOLS_METHOD" = "x" || "x$URLTOOLS_METHOD" = "xperl" ) ]]; then
  25. if perl -MURI::Encode -e 1&> /dev/null; then
  26. alias urlencode='perl -MURI::Encode -ep "uri_encode($ARGV[0]);"'
  27. alias urldecode='perl -MURI::Encode -ep "uri_decode($ARGV[0]);"'
  28. elif perl -MURI::Escape -e 1 &> /dev/null; then
  29. alias urlencode='perl -MURI::Escape -ep "uri_escape($ARGV[0]);"'
  30. alias urldecode='perl -MURI::Escape -ep "uri_unescape($ARGV[0]);"'
  31. else
  32. alias urlencode="perl -e '\$new=\$ARGV[0]; \$new =~ s/([^A-Za-z0-9])/sprintf(\"%%%02X\", ord(\$1))/seg; print \"\$new\n\";'"
  33. alias urldecode="perl -e '\$new=\$ARGV[0]; \$new =~ s/\%([A-Fa-f0-9]{2})/pack(\"C\", hex(\$1))/seg; print \"\$new\n\";'"
  34. fi
  35. fi
  36. unset URLTOOLS_METHOD