From d16f0d14af5ae37597ddd3087277ac2598479358 Mon Sep 17 00:00:00 2001 From: Henrik Lissner Date: Tue, 25 Apr 2017 02:58:25 -0400 Subject: [PATCH] Refactor bin/{duckduckgo,urlencode} --- bin/duckduckgo | 13 +------------ bin/urlencode | 13 +++++++++---- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/bin/duckduckgo b/bin/duckduckgo index 9da45945..fd296bdd 100755 --- a/bin/duckduckgo +++ b/bin/duckduckgo @@ -1,16 +1,5 @@ #!/usr/bin/env bash -urlencode() { - local LANG=C - for ((i=0;i<${#1};i++)); do - if [[ ${1:$i:1} =~ ^[a-zA-Z0-9\.\~\_\-]$ ]]; then - printf "${1:$i:1}" - else - printf '%%%02X' "'${1:$i:1}" - fi - done -} - -query=$(urlencode "$*") +query=$(urlencode <<< "$*") echo "Opening https://duckduckgo.com/?q=$query" open "https://duckduckgo.com/?q=$query" diff --git a/bin/urlencode b/bin/urlencode index db976837..c7bfd08a 100755 --- a/bin/urlencode +++ b/bin/urlencode @@ -1,7 +1,12 @@ #!/usr/bin/env python -import os, sys, urllib -if os.isatty(file.fileno(sys.stdin)): - text = sys.argv[1] +import sys +try: + from urllib.parse import quote_plus +except ImportError: + from urllib import quote_plus + +if sys.argv[1:]: + text = " ".join(sys.argv[1:]) else: text = "".join(sys.stdin.readlines()) -print(urllib.quote_plus(text.strip())) +print(quote_plus(text.strip()))