comparison bin/addwhatis @ 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
children
comparison
equal deleted inserted replaced
12231:44379732c06b 12232:0124f9ed4c49
1 #!/usr/bin/python3
2 import sys, os, re, getopt
3 # allow options for future compatibility
4 opts, args = getopt.getopt(sys.argv[1:], "")
5 newd = dict()
6 def procnew(arg):
7 match = re.fullmatch(r"([^\x00\r\n()]+\([0-9A-Z_a-z]+\))"
8 r"(?: ?| - ([^\x00\r\n]*?))\r?\n?", arg)
9 if match:
10 key, val = match.group(1), match.group(2)
11 if key in newd:
12 print("addwhatis: duplicate key in input: %r" % (key,), file = sys.stderr)
13 sys.exit(2)
14 else:
15 newd[key] = val
16 else:
17 print("addwhatis: cannot parse input as whatis line or whatis key: %r" % (line,), file = sys.stderr)
18 sys.exit(2)
19 if args:
20 for arg in args:
21 procnew(arg)
22 else:
23 for line in sys.stdin:
24 procnew(line)
25 sharedir = os.environ.get("HACKENV", "/hackenv") + "/share"
26 inputfname = sharedir + "/whatis"
27 outputfname = sharedir + "/whatis.tmp"
28 with open(inputfname, errors = "surrogateescape", newline = "\n") as inputf, \
29 open(outputfname, "x", errors = "surrogatepass") as outputf:
30 for line in inputf:
31 keep = True
32 match = re.match(r"([^\x00\r\n()]+\([0-9A-Z_a-z]+\)) - ", line)
33 if match:
34 key = match.group(1)
35 if key in newd:
36 keep = False
37 if None == newd[key]:
38 print("addwhatis: dropped %r" % (key,), file = sys.stderr)
39 else:
40 outputf.write("%s - %s\n" % (key, newd[key]))
41 print("addwhatis: replaced %r" % (key,), file = sys.stderr)
42 del newd[key]
43 if keep:
44 outputf.write(line)
45 for key, val in newd.items():
46 outputf.write("%s - %s\n" % (key, val))
47 print("addwhatis: added %r" % (key,), file = sys.stderr)
48 os.rename(outputfname, inputfname)
49