helm/bin/uri
2017-12-06 01:39:10 -05:00

38 lines
1.2 KiB
Python
Executable file

#!/usr/bin/env python
"""
Encode/decode url strings in stdin or the given file(s).
"""
import argparse
import fileinput
try:
from urllib.parse import quote_plus, quote, unquote_plus, unquote
except ImportError:
from urllib import quote_plus, quote, unquote_plus, unquote
def main():
opts = argparse.ArgumentParser(description="Make text URI-safe by encoding/decoding input")
opts.add_argument('file', type=str, nargs='*', help='File(s) to encode/decode')
opts.add_argument('-e', '--encode', action='store_true', help='Use encoder')
opts.add_argument('-E', '--encode-plus', action='store_true', help='Use encoder, but encode spaces as pluses')
opts.add_argument('-d', '--decode', action='store_true', help='Use decoder')
opts.add_argument('-D', '--decode-plus', action='store_true', help='Use decoder, but decode pluses as spaces')
args = opts.parse_args()
action = quote
if args.decode:
action = unquote
elif args.decode_plus:
action = unquote_plus
elif args.encode_plus:
action = quote_plus
text = [line for line in fileinput.input(args.file)]
print(action("\n".join(text).strip()))
if __name__ == '__main__':
main()