home · contact · privacy
Server/py: Add tokenizer function.
[plomrogue] / plomrogue-server.py
1 import argparse
2 import errno
3 import os
4 import time
5
6
7 class HandledException(Exception):
8     """Feature-less Exception child. Use for expected operational errors."""
9
10     pass
11
12
13 def setup_server_io(io_db):
14     """Fill IO files DB with proper file( path)s. Write process IO test string.
15
16     Ensure IO files directory at server/. Remove any old in file if found. Set
17     up new in file (io_db["file_in"]) for reading at io_db["path_in"], and new
18     out file (io_db["file_out"]) for writing at io_db["path_out"]. Start out
19     file with process hash line of format PID + " " + floated UNIX time
20     (io_db["teststring"]). Set worldstate file path io_db["path_worldstate"].
21     """
22     io_dir = "server/"
23     io_db["path_in"] = io_dir + "in"
24     io_db["path_out"] = io_dir + "out"
25     io_db["path_worldstate"] = io_dir + "worldstate"
26     io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
27     os.makedirs(io_dir, exist_ok=True)
28     io_db["file_out"] = open(io_db["path_out"], "w")
29     io_db["file_out"].write(io_db["teststring"] + "\n")
30     if os.access(io_db["path_in"], os.F_OK):
31         os.remove(io_db["path_in"])
32     io_db["file_in"] = open(io_db["path_in"], "w")
33     io_db["file_in"].close()
34     io_db["file_in"] = open(io_db["path_in"], "r")
35
36
37 def cleanup_server_io(io_db):
38     """Close and remove all files open in IO files DB."""
39     def helper(file_key, path_key):
40         if file_key in io_db:
41             io_db[file_key].close()
42             os.remove(io_db[path_key])
43     helper("file_out", "path_out")
44     helper("file_in", "path_in")
45     helper("file_worldstate", "path_worldstate")
46
47
48 def detect_atomic_leftover(path):
49     """Raise explained HandledException if file is found at path + "_tmp"."""
50     path_tmp = path + "_tmp"
51     msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
52           "aborted previous attempt to write '" + path + "'. Aborting until " \
53           "the matter is resolved by removing it from its current path."
54     if os.access(path_tmp, os.F_OK):
55         raise HandledException(msg)
56
57
58 def obey(msg):
59     """"""
60     print("Input: " + msg)
61
62
63 def tokenize(string):
64     """Divide string by " ", \t and quotes (that also group). Escape with \."""
65     charlist_A = list(string)
66     i = 0
67     for c in charlist_A:
68         if "\\" == c and i < len(charlist_A) - 1:
69             charlist_A[i] = "remove"
70             charlist_A[i + 1] = charlist_A[i + 1] + "_escaped"
71         i = i + 1
72     charlist_B = []
73     for c in charlist_A:
74         if "remove" != c:
75             charlist_B.append(c)
76     in_quotes = 0
77     i = 0
78     for c in charlist_B:
79         if "\"" == c:
80             in_quotes = 0 if in_quotes else 1
81             if i < len(charlist_B) - 1:
82                 charlist_B[i] = "separator"
83         elif (not in_quotes) and (" " == c or "\t" == c):
84             charlist_B[i] = "separator"
85         i = i + 1
86     list_of_charlists = [[]]
87     i = 0
88     for c in charlist_B:
89         if "separator" == c:
90             if [] != list_of_charlists[-1]:
91                 list_of_charlists.append([])
92                 i = i + 1
93         else:
94             list_of_charlists[i].append(c[0])
95     tokens = []
96     for charlist in list_of_charlists:
97         tokens.append("".join(charlist))
98     return tokens
99
100
101 io_db = {}
102 try:
103     parser = argparse.ArgumentParser()
104     parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
105                         action='store')
106     opts, unknown = parser.parse_known_args()
107     setup_server_io(io_db)
108     # print("DUMMY: Run game.")
109     path_recordfile = "recordfile"
110     path_savefile = "savefile"
111     detect_atomic_leftover(path_savefile)
112     detect_atomic_leftover(path_recordfile)
113     if None != opts.replay:
114         if opts.replay < 1:
115             opts.replay = 1
116         print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
117               " (if so late  a turn is to be found).")
118         if not os.access(path_savefile, os.F_OK):
119             raise HandledException("No record file found to replay.")
120     elif os.access(path_savefile, os.F_OK):
121         print(open(path_savefile, "r").read())
122     else:
123         msg = "MAKE_WORLD " + str(int(time.time()))
124         obey(msg)
125 except SystemExit:
126     pass
127 except HandledException as exception:
128     print("ABORTING: " + exception.args[0])
129 except:
130     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
131     raise
132 finally:
133     cleanup_server_io(io_db)
134     # print("DUMMY: (Clean up C heap.)")