view bin/addwhatis @ 12320:9c7eb9899d95 draft

<fizzie> le/rn karma//All living beings have actions (karma) as their own, their inheritance, their congenital cause, their kinsman, their refuge. It is karma that differentiates beings into low and high states.
author HackEso <hackeso@esolangs.org>
date Fri, 06 Mar 2020 23:08:37 +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)