-
Notifications
You must be signed in to change notification settings - Fork 0
/
myutils.py
427 lines (357 loc) · 10.5 KB
/
myutils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# myutils.py
import sys, re, io, pytest
reAllWS = re.compile(r'^\s*$')
reLeadWS = re.compile(r'^([\t\ ]+)') # don't consider '\n'
reLeadTabs = re.compile(r'^(\t*)')
reTrailWS = re.compile(r'\s+$')
reTrailNL = re.compile(r'\n$')
reNonSepChar = re.compile(r'^[A-Za-z0-9_\s]')
reFirstWord = re.compile(r'^\s*(\S+)')
reAssign = re.compile(r'^\s*(\S+)\s*\=\s*(.*)$')
hSpecial = {
"\t": "\\t",
"\n": "\\n",
" " : "\\s",
}
# ---------------------------------------------------------------------------
def splitAssignment(s):
assert type(s) == str
result = reAssign.search(s)
if result:
return (result.group(1), result.group(2))
else:
raise Exception(f"String '{s}' is not an assignment statement")
# ---------------------------------------------------------------------------
def rmPrefix(lLines, *, debug=False, skipEmptyLines=True):
# --- Normally lLines is a list of strings, but you can pass in
# a string with internal '\n' characters
#
# --- A line consisting of only whitespace, is considered empty
# leading and trailing empty lines don't appear in output
# internal empty lines appear as empty lines, but
# no exception for the missing prefix
# --- Check the type of the parameter ---
if isinstance(lLines, str):
if debug:
print(f"DEBUG: String passed, splitting into lines")
lNewLines = rmPrefix(io.StringIO(lLines).readlines())
return ''.join(lNewLines)
elif type(lLines) is not list:
typ = type(lLines)
raise TypeError(f"rmPrefix(): Invalid parameter, type = {typ}")
if len(lLines) == 0:
if debug:
print(f"DEBUG: Zero lines - return empty list")
return []
firstLine = lLines[0] # first line
nextPos = 1
if debug:
print(f"DEBUG: firstLine set to '{traceStr(firstLine)}'")
lNewLines = [] # this will be returned
# --- Skip past any empty lines
# NOTE: If skipEmptyLines is False, the empty lines are
# included, but not considered for determining the prefix
while isAllWhiteSpace(firstLine) and (nextPos < len(lLines)):
if skipEmptyLines:
if debug:
print(f"DEBUG: Line at pos {nextPos-1} '{traceStr(firstLine)}'"
" is empty - skipping")
else:
if line[-1] == '\n':
lNewLines.append('\n')
if debug:
print(f"DEBUG: Add line at pos {nextPos-1} '\\n'")
else:
lNewLines.append('')
if debug:
print(f"DEBUG: Add line at pos {nextPos-1} ''")
firstLine = lLines[nextPos]
if debug:
print(f"DEBUG: firstLine reset to '{traceStr(firstLine)}'")
nextPos += 1
if (isAllWhiteSpace(firstLine)):
if debug:
print(f"DEBUG: All lines empty - return empty list")
return []
if debug:
print(f"DEBUG: First non-empty line '{traceStr(firstLine)}'"
f" found at pos {nextPos-1}")
result = reLeadWS.match(firstLine)
if not result:
if debug:
print(f"DEBUG: No prefix found - return remaining lines,"
f" sripping trailing empty lines")
lNewLines = lLines[nextPos:]
while (len(lNewLines) > 0) and isAllWhiteSpace(lNewLines[-1]):
del lNewLines[-1]
return lNewLines # nothing to strip off
leadWS = result.group(1)
nChars = len(leadWS)
assert nChars > 0 # due to regexp used
if debug:
print(f"DEBUG: Prefix '{traceStr(leadWS)}'"
f" consists of {nChars} chars")
# --- Create an entirely new array
# Add first line, with prefix stripped off
lNewLines.append(firstLine[nChars:])
if debug:
print(f"DEBUG: Add line '{traceStr(firstLine[nChars:])}'")
for line in lLines[nextPos:]:
if isAllWhiteSpace(line):
if skipEmptyLines:
if debug:
print(f"DEBUG: Skip empty line")
else:
if line[-1] == '\n':
lNewLines.append('\n')
if debug:
print(f"DEBUG: Add line '\\n'")
else:
lNewLines.append('')
if debug:
print(f"DEBUG: Add line ''")
else:
pos = line.find(leadWS)
if pos == 0:
# --- remove the prefix
lNewLines.append(line[nChars:])
if debug:
print(f"DEBUG: Add line '{traceStr(line[nChars:])}'")
else:
raise SyntaxError("rmPrefix(): Bad indentation")
if skipEmptyLines:
# --- Strip off trailing WS lines
while (len(lNewLines) > 0) and isAllWhiteSpace(lNewLines[-1]):
del lNewLines[-1]
if debug:
print(f"DEBUG: Remove last line")
if debug:
print(lNewLines)
return lNewLines
# ---------------------------------------------------------------------------
def isAllWhiteSpace(s):
assert type(s) == str
if reAllWS.match(s):
return True
else:
return False
# ---------------------------------------------------------------------------
def isSeparator(s, testch=None):
# --- a string is a separator if:
# 1. string is not empty
# 2. all chars are the same
# 3. the char is not a letter, digit, '_' or whitespace
# return value is the character - of length 1
# If testch is provided, return value will be None
# unless the separator char matches it
assert type(s) == str
if (len(s) == 0):
return None
ch0 = s[0]
if reNonSepChar.search(ch0):
return None
for ch in s[1:]:
if ch != ch0:
return None
if testch:
assert len(testch) == 1
if (ch0 != testch):
return None
return ch0
# ---------------------------------------------------------------------------
def firstWordOf(s):
assert type(s) == str
result = reFirstWord.search(s)
if result:
return result.group(1)
else:
return None
# ---------------------------------------------------------------------------
def getHereDoc(fh):
# --- Allow passing in a string
if isinstance(fh, str):
fh = io.StringIO(fh)
lLines = []
line = fh.readline()
while line and not reAllWS.match(line):
lLines.append(line)
line = fh.readline()
return rmPrefix(lLines)
# ---------------------------------------------------------------------------
def getMethod(aClass, methodName):
try:
return getattr(aClass, methodName)
except AttributeError:
return None
# ---------------------------------------------------------------------------
def getFunc(aModule, funcName):
try:
return getattr(aModule, funcName)
except AttributeError:
return None
# ---------------------------------------------------------------------------
def traceStr(str, *, maxchars=0, detailed=False):
nTabs = 0
nChars = 0
outstr = ''
result = reLeadTabs.search(str)
totTabs = len(result.group(1))
for ch in str:
if (maxchars > 0) and (nChars >= maxchars): break
if ch in hSpecial:
outch = hSpecial[ch]
else:
i = ord(ch)
if (i < 32) or (i > 126):
outch = f"ASCII{i}"
else:
outch = ch
if detailed:
print(f"CHAR: '{outch}'")
outstr += outch
nChars += 1
return outstr
# ---------------------------------------------------------------------------
def cleanup_testcode(glob, *, debug=False):
# --- If not running unit tests, remove unneeded functions and data
# to save memory
if sys.argv[0].find('pytest') == -1:
if debug:
print(f"Running normally - clean up {glob['__file__']} test functions/data")
reTest = re.compile(r'^(?:test|init)_')
for name in [name for name in glob.keys() if reTest.match(name)]:
if debug:
print(f"Clean up {name}")
globals()[name] = None
else:
if debug:
print("Running unit tests")
# ---------------------------------------------------------------------------
# UNIT TESTS
# ---------------------------------------------------------------------------
def test_1():
with pytest.raises(TypeError):
s = rmPrefix(5)
def test_2():
with pytest.raises(TypeError):
s = rmPrefix((3,4,5))
def test_21():
from TreeNode import TreeNode
with pytest.raises(TypeError):
s = rmPrefix(TreeNode('label'))
# --- Make sure these things are tested - for strings & lists of strings
# 1. By default, any whitespace lines are removed
# 2. Internal whitespace lines are included
# 3. Trailing newlines are untouched
def test_3():
# --- Basic example - find leading whitespace in first line
# and strip that from all other lines
lNewLines = rmPrefix([
"\t\tabc",
"\t\t\tdef",
"\t\t\t\tghi",
])
assert lNewLines == [
"abc",
"\tdef",
"\t\tghi",
]
def test_30():
assert rmPrefix([]) == []
def test_31():
# --- leading and trailing all-whitespace lines are removed
lNewLines = rmPrefix([
"",
"\t \t",
"\t\t\n",
"\t\tabc",
"\t\t\tdef",
"\t\t\t\tghi",
"\t\t",
])
assert lNewLines == [
"abc",
"\tdef",
"\t\tghi",
]
def test_4():
s = '''
abc
def
ghi
'''
lNewStr = rmPrefix(s)
assert lNewStr == 'abc\n\tdef\n\t\tghi\n'
def test_5():
# --- test the utility function getHereDoc()
s = '''
menubar
file
new
handler <<<
my $evt = $_[0];
$evt.createNewFile();
return undef;
open
edit
undo
'''
fh = io.StringIO(s)
line1 = fh.readline() # a blank line
line2 = fh.readline() # menubar
line3 = fh.readline() # file
line4 = fh.readline() # new
line5 = fh.readline() # handler <<<
assert line5.find('<<<') == 13
lLines = getHereDoc(fh)
assert len(lLines) == 3
line6 = fh.readline() # open
assert(line6.find('open') == 4)
def test_6():
assert not isSeparator('')
assert not isSeparator('X')
assert not isSeparator('x')
assert not isSeparator('_')
assert not isSeparator('4')
assert not isSeparator(' ')
assert not isSeparator('\t')
assert isSeparator('-') == '-'
assert isSeparator('-----') == '-'
assert isSeparator('----------------') == '-'
assert not isSeparator('abc')
assert isSeparator('=====') == '='
assert not isSeparator(' -')
assert not isSeparator('- ')
assert isSeparator('-', '-')
assert isSeparator('-----', '-')
assert isSeparator('----------------', '-')
assert isSeparator('=====', '=')
assert isSeparator('=====', '=')
def test_7():
assert firstWordOf('abc def') == 'abc'
assert firstWordOf('') == None
assert firstWordOf(' ') == None
assert firstWordOf(' abc def ghi') == 'abc'
def test_8():
# --- Test my understanding of the split method
assert ("abc xyz".split()[0] == 'abc')
assert (" abc xyz ".split()[0] == 'abc')
assert (" abc xyz ".split()[1] == 'xyz')
assert (" 房子 窗口 ".split()[0] == '房子')
assert (" 房子 窗口 ".split()[1] == '窗口')
def test_9():
assert splitAssignment("x = 9") == ('x', '9')
assert splitAssignment("xxx = 90") == ('xxx', '90')
assert splitAssignment(" x = 9") == ('x', '9')
assert splitAssignment("x=9") == ('x', '9')
def test_10():
with pytest.raises(Exception):
result = splitAssignment("x9")
def test_11():
try:
(key, value) = splitAssignment('name = editor')
assert key == 'name'
assert value == 'editor'
except:
raise Exception("Very Bad")
cleanup_testcode(globals())