From 273333361965253595d22722d9ddbdf67115b6a4 Mon Sep 17 00:00:00 2001 From: Henrik Lissner Date: Mon, 3 Jul 2017 18:13:08 +0200 Subject: [PATCH] Rename urlencode => url & rewrite --- bin/url | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++ bin/urlencode | 12 ----------- 2 files changed, 58 insertions(+), 12 deletions(-) create mode 100755 bin/url delete mode 100755 bin/urlencode diff --git a/bin/url b/bin/url new file mode 100755 index 00000000..e81bd57a --- /dev/null +++ b/bin/url @@ -0,0 +1,58 @@ +#!/usr/bin/env python + +# Encode/decode url strings in stdin or the given file(s). + +import getopt +import fileinput +import sys +import os +try: + from urllib.parse import quote_plus, quote, unquote_plus, unquote +except ImportError: + from urllib import quote_plus, quote, unquote_plus, unquote + +# +def encode(text, plus=False): + return quote(text.strip()) + +def encode_plus(text): + return quote_plus(text.strip()) + +def decode(text): + return unquote(text.strip()) + +def decode_plus(text): + return unquote_plus(text.strip()) + +def usage(): + # TODO Improve this + print("Usage: {} [-edEDh] file1[ file2[ ...]]".format(os.path.basename(sys.argv[0]))) + +# +if __name__ == '__main__': + COMMANDS = { + "-e": encode, + "-E": encode_plus, + "-d": decode, + "-D": decode_plus + } + + try: + optlist, args = getopt.getopt(sys.argv[1:], 'edEDh') + sys.argv = [sys.argv[0]] + args + except getopt.GetoptError as err: + print(err) + sys.exit(1) + + action = encode + for o, a in optlist: + if o in COMMANDS: + action = COMMANDS[o] + elif o == '-h': + usage() + sys.exit() + else: + assert False, "unhandled option" + + input = "\n".join([line for line in fileinput.input()]) + print(action(input)) diff --git a/bin/urlencode b/bin/urlencode deleted file mode 100755 index c7bfd08a..00000000 --- a/bin/urlencode +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env python -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(quote_plus(text.strip()))