view bin/addwhatis @ 12256:821155c00e34 draft

<fizzie> ` sed -e \'s|wisdom|bin|\' < ../bin/culprits > ../bin/cblprits; chmod a+x ../bin/cblprits
author HackEso <hackeso@esolangs.org>
date Sat, 07 Dec 2019 23:36:22 +0000
parents 0124f9ed4c49
children
line wrap: on
line source

#!/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)