changeset 12232:0124f9ed4c49 draft

<b_jonas> fetch /hackenv/bin/addwhatis https://hack.esolangs.org/get/bin/addwhatis
author HackEso <hackeso@esolangs.org>
date Thu, 05 Dec 2019 21:01:29 +0000
parents 44379732c06b
children cc8d3fec0222
files bin/addwhatis
diffstat 1 files changed, 49 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /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)
+