# HG changeset patch # User HackEso # Date 1575579689 0 # Node ID 0124f9ed4c4981fa6fa2b8a5335f0414ddfb65c4 # Parent 44379732c06bc9d4730b51f29d676461ed8c9276 fetch /hackenv/bin/addwhatis https://hack.esolangs.org/get/bin/addwhatis diff -r 44379732c06b -r 0124f9ed4c49 bin/addwhatis --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/bin/addwhatis Thu Dec 05 21:01:29 2019 +0000 @@ -0,0 +1,49 @@ +#!/usr/bin/python3 +import sys, os, re, getopt +# allow options for future compatibility +opts, args = getopt.getopt(sys.argv[1:], "") +newd = dict() +def procnew(arg): + match = re.fullmatch(r"([^\x00\r\n()]+\([0-9A-Z_a-z]+\))" + r"(?: ?| - ([^\x00\r\n]*?))\r?\n?", arg) + if match: + key, val = match.group(1), match.group(2) + if key in newd: + print("addwhatis: duplicate key in input: %r" % (key,), file = sys.stderr) + sys.exit(2) + else: + newd[key] = val + else: + print("addwhatis: cannot parse input as whatis line or whatis key: %r" % (line,), file = sys.stderr) + sys.exit(2) +if args: + for arg in args: + procnew(arg) +else: + for line in sys.stdin: + procnew(line) +sharedir = os.environ.get("HACKENV", "/hackenv") + "/share" +inputfname = sharedir + "/whatis" +outputfname = sharedir + "/whatis.tmp" +with open(inputfname, errors = "surrogateescape", newline = "\n") as inputf, \ + open(outputfname, "x", errors = "surrogatepass") as outputf: + for line in inputf: + keep = True + match = re.match(r"([^\x00\r\n()]+\([0-9A-Z_a-z]+\)) - ", line) + if match: + key = match.group(1) + if key in newd: + keep = False + if None == newd[key]: + print("addwhatis: dropped %r" % (key,), file = sys.stderr) + else: + outputf.write("%s - %s\n" % (key, newd[key])) + print("addwhatis: replaced %r" % (key,), file = sys.stderr) + del newd[key] + if keep: + outputf.write(line) + for key, val in newd.items(): + outputf.write("%s - %s\n" % (key, val)) + print("addwhatis: added %r" % (key,), file = sys.stderr) +os.rename(outputfname, inputfname) +