Files

62 lines
3.1 KiB
Python
Executable File

#!/usr/bin/env python3
# urlfile — URL-encode/decode a file or a string, with a report of what changed.
# Usage: urlfile [--decode] [--string TEXT] [--plus] input [output]
"""urlfile: percent-encoding for files and strings. Encodes a whole file
(useful for data: URIs and query payloads), decodes back, and with --string
works on a literal argument — reporting how many characters were escaped so
you can see at a glance whether the input needed encoding at all."""
import argparse, sys
import urllib.parse
def encode_bytes(data, plus=False):
fn = urllib.parse.quote_plus if plus else urllib.parse.quote
return fn(data.decode("utf-8", "surrogateescape") if isinstance(data, bytes) else data)
def run(inp, out, decoding=False, string=None, plus=False):
if string is not None:
text = urllib.parse.unquote_plus(string) if decoding else (urllib.parse.quote_plus(string) if plus else urllib.parse.quote(string))
if out: open(out, "w").write(text)
else: print(text)
n = sum(1 for c in string if c in "%+" ) if decoding else sum(1 for c in text if c == "%")
print(f"urlfile: {n} percent-sequences {'decoded' if decoding else 'produced'}", file=sys.stderr)
return 0
data = open(inp, "rb").read() if inp != "-" else sys.stdin.buffer.read()
if decoding:
try: result = urllib.parse.unquote_to_bytes(data.decode("ascii"))
except Exception as e:
print(f"urlfile: invalid percent-encoding: {e}", file=sys.stderr); return 1
if out: open(out, "wb").write(result)
else: sys.stdout.buffer.write(result)
else:
text = urllib.parse.quote_from_bytes(data, safe="/") if not plus else urllib.parse.quote_plus_from_bytes(data)
if out: open(out, "w").write(text)
else: sys.stdout.write(text)
return 0
def selftest():
import tempfile, os
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "a.txt"); open(src, "wb").write(b"hello world & caf\xc3\xa9?x=1")
enc = os.path.join(d, "a.url"); dec = os.path.join(d, "a.out")
assert run(src, enc) == 0
assert "%20" in open(enc).read() or "%26" in open(enc).read()
assert run(enc, dec, decoding=True) == 0
assert open(dec, "rb").read() == open(src, "rb").read()
assert run(None, None, string="a b&c") == 0
print("urlfile selftest: PASS"); return 0
def main():
ap = argparse.ArgumentParser(description="URL-encode/decode a file or a literal string.")
ap.add_argument("input", nargs="?"); ap.add_argument("output", nargs="?")
ap.add_argument("--decode", "-d", action="store_true")
ap.add_argument("--string", help="encode/decode this literal string instead of a file")
ap.add_argument("--plus", action="store_true", help="encode spaces as + (form encoding)")
ap.add_argument("--selftest", action="store_true")
a = ap.parse_args()
if a.selftest: return selftest()
if a.string is None and not a.input: ap.error("need an input file or --string")
return run(a.input, a.output, a.decode, a.string, a.plus)
if __name__ == "__main__":
sys.exit(main())