ipo_process.html


001| """IPO Implementation -- Processes.
001| 
001| Classes:
001|     ipo_proc_nop (ipo_process)                  ~NOP Process subclass
001|     ipo_proc_ascii (ipo_process)                ~ASCII Process subclass
001|     ipo_proc_change (ipo_process)               ~Change Process subclass
001| 
001|     ipo_proc_rot13 (ipo_process)                ~ROT13 Process class
001|     ipo_proc_tab_2_spc (ipo_process)            ~Expand TABs to spaces Process subclass
001| 
001|     ipo_proc_find (ipo_process)                 ~Find Process class
001|     ipo_proc_regex (ipo_process)                ~RegEx Process subclass
001| 
001|     ipo_proc_fields (ipo_process)               ~Extract Fields Process subclass
001| 
001| """

002| ####################################################################################################
003| from re import compile as re_compile, RegexFlag
004| from logger import logger
005| from goodies import typename, KWARG, rot13
006| from files import EOL, TAB
007| from ipo_defs import ipo_token, ipo_process, EOL_TAG, SPC_TAG, SEP_TAG
008| ####################################################################################################
009| Log = logger('Process')
010| 
011| 
012| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
013| class ipo_proc_nop (ipo_process):
014|     """NOP Process subclass."""
015|     tag = 'any'
016| 
017|     def __init__ (self, **kwargs):
018|         """New NOP Process instance."""
019|         super().__init__('NOP')
020| 
021|     def __call__ (self, datum):
022|         """Process next chunk of data."""
023|         if datum is None:
024|             self.status = -1
025|             return None
026|         super().__call__(datum)
027|         return datum
028| 
029| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
030| class ipo_proc_ascii (ipo_process):
031|     """ASCII Process subclass."""
032|     tag = 'Text'
033|     CtrlCharBase = ord('@')
034|     SpaceIndex = ord(' ')
035| 
036|     def __init__ (self, **kwargs):
037|         """New ASCII Process instance."""
038|         super().__init__('ASCII')
039| 
040|     def __call__ (self, datum):
041|         """Process next chunk of data."""
042|         if datum is None:
043|             self.status = -1
044|             return None
045|         super().__call__(datum)
046|         return [self.charfunc(d) for d in datum]
047| 
048|     def charfunc (self, datum):
049|         ch = datum()
050|         cx = ord(ch)
051|         # Above ASCII range...
052|         if 0x7f <= cx:
053|             # Non-ASCII; return "U+XXXX" code...
054|             datum(f'\\U+{cx:04x}')
055|             return datum
056|         # ASCII char or \n, \r, \t...
057|         if (self.SpaceIndex <= cx) or (cx in [9, 10, 13]):
058|             # Just return the character...
059|             return datum
060|         # Return Control Code string (e.g. ^Z)...
061|         datum(f'^{chr(cx+self.CtrlCharBase)}')
062|         return datum
063| 
064| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
065| class ipo_proc_change (ipo_process):
066|     """Change Process subclass."""
067|     tag = 'Text'
068| 
069|     def __init__ (self, **kwargs):
070|         """New Change Process instance."""
071|         super().__init__('Change')
072|         self.force_case = KWARG('case', '', str, kwargs)
073|         self.bit_mask = KWARG('mask', 0, int, kwargs)
074|         self.rev = KWARG('rev', 0, int, kwargs)
075| 
076|     def __call__ (self, datum):
077|         """Process next chunk of data."""
078|         if datum is None:
079|             self.status = -1
080|             return None
081|         super().__call__(datum)
082| 
083|         # Reverse order...
084|         if self.rev:
085|             # Ignore newline...
086|             if datum[-1]() == EOL:
087|                 tail = datum.pop()
088|                 datum = list(reversed(datum))
089|                 datum.append(tail)
090|             else:
091|                 datum = list(reversed(datum))
092| 
093|         # Force case...
094|         match self.force_case:
095|             case 'lc':
096|                 for d in datum:
097|                     val = d()
098|                     d(val.lower())
099|             case 'uc':
100|                 for d in datum:
101|                     val = d()
102|                     d(val.upper())
103|             case 'ttl':
104|                 for d in datum:
105|                     val = d()
106|                     d(val.title())
107|             case _:
108|                 pass
109| 
110|         # Apply bitmask...
111|         if self.bit_mask:
112|             for d in datum:
113|                 val = d()
114|                 d(chr(ord(val) & self.bit_mask))
115| 
116|         return datum
117| 
118| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
119| class ipo_proc_rot13 (ipo_process):
120|     """ROT13 Process subclass."""
121|     tag = 'Text'
122| 
123|     def __init__ (self, **kwargs):
124|         """New ROT13 Process instance."""
125|         super().__init__('ROT13')
126| 
127|     def __call__ (self, datum):
128|         """Process next chunk of data."""
129|         if datum is None:
130|             self.status = -1
131|             return None
132|         super().__call__(datum)
133|         for d in datum:
134|             val = d()
135|             d(rot13(val))
136|         return datum
137| 
138| 
139| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
140| class ipo_proc_tab_2_spc (ipo_process):
141|     """Expand TABs to spaces Process subclass."""
142|     tag = 'Text'
143| 
144|     def __init__ (self, **kwargs):
145|         """New Expand TABs Process instance."""
146|         super().__init__('Tabs')
147|         self.tabs = KWARG('tabs', 8, int, kwargs)
148|         self.delim = KWARG('delim', ' ', str, kwargs)
149|         self.char_ctr = 0
150| 
151|     def __call__ (self, datum):
152|         """Process next chunk of data."""
153|         if datum is None:
154|             self.status = -1
155|             return None
156|         super().__call__(datum)
157|         buf = []
158|         for dx,d in enumerate(datum):
159|             val = d()
160|             # Line end chars reset the line counter...
161|             if val in [EOL, '\r']:
162|                 buf.append(d)
163|                 self.char_ctr = 0
164|                 continue
165|             # TAB character...
166|             if val == TAB:
167|                 div,rem = divmod(self.char_ctr, self.tabs)
168|                 last_tab = (self.char_ctr // self.tabs) * self.tabs
169|                 next_tab = last_tab + self.tabs
170|                 spcs = next_tab - self.char_ctr
171|                 buf.extend(ipo_token(self.delim,d.row,d.col,SPC_TAG) for _ in range(spcs))
172|                 self.char_ctr = next_tab
173|                 continue
174|             # Ordinary character; just increment counter...
175|             buf.append(d)
176|             self.char_ctr += 1
177|         #
178|         return buf
179| 
180| 
181| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
182| class ipo_proc_find (ipo_process):
183|     """Find Process subclass."""
184|     tag = 'Text'
185| 
186|     def __init__ (self, **kwargs):
187|         """New Find Process instance."""
188|         super().__init__('Find')
189|         self.find_string = KWARG('find', 'ZCZC', str, kwargs)
190|         self.invert_out = KWARG('not', 0, int, kwargs)
191|         # Multiple fields...
192|         if '|' in self.find_string:
193|             self.search_for = self.find_string.split('|')
194|         else:
195|             self.search_for = [self.find_string]
196| 
197|     def __call__ (self, datum):
198|         """Process next chunk of data."""
199|         if datum is None:
200|             self.status = -1
201|             return None
202|         super().__call__(datum)
203| 
204|         line = ''.join(d() for d in datum)
205|         if self._search(line):
206|             # Search string is in text...
207|             return ([] if self.invert_out else datum)
208|         # Search string is NOT in text...
209|         return (datum if self.invert_out else [])
210| 
211|     def _search (self, line):
212|         """Scan line for multiple patterns."""
213|         for patt in self.search_for:
214|             if patt in line:
215|                 return True
216|         # Didn't find it...
217|         return False
218| 
219| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
220| class ipo_proc_regex (ipo_process):
221|     """RegEx Process subclass."""
222|     tag = 'Text'
223| 
224|     def __init__ (self, **kwargs):
225|         """New RegEx Process instance."""
226|         super().__init__('RegEx')
227|         self.search_for = KWARG('find', '', str, kwargs)
228|         self.invert_out = KWARG('not', 0, int, kwargs)
229|         self.regex = re_compile(self.search_for, RegexFlag.IGNORECASE)
230| 
231|     def __call__ (self, datum):
232|         """Process next chunk of data."""
233|         if datum is None:
234|             self.status = -1
235|             return None
236|         super().__call__(datum)
237| 
238|         line = ''.join(d() for d in datum)
239|         res = self.regex.search(line)
240|         if res:
241|             # Search string in text...
242|             return (None if self.invert_out else datum)
243|         # Search string not in text...
244|         return (datum if self.invert_out else [])
245| 
246| 
247| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
248| class ipo_proc_fields (ipo_process):
249|     """Extract Fields Process subclass. Field Spec: 1:10,20:24,60:999"""
250|     tag = 'Line'
251| 
252|     def __init__ (self, **kwargs):
253|         """New ExtractFields Process instance."""
254|         super().__init__('Fields')
255|         self.colspec = KWARG('cols', '', str, kwargs)
256|         self.delim = KWARG('delim', ' ', str, kwargs)
257|         Log.debug(f'{self.colspec=}')
258|         Log.debug(f'{self.delim=}')
259| 
260|         # Split colspec into parts...
261|         self.parts = self.colspec.split(',')
262|         Log.debug(f'{self.parts=}')
263| 
264|         # Split parts into start/stop specs...
265|         self.specs = [field.split(':') for field in self.parts]
266|         Log.debug(f'{self.specs=}')
267| 
268|         # Convert start/stop specs to ranges...
269|         self.fields = []
270|         for start,stop in self.specs:
271|             s0 = 0 if start=='*' else int(start)
272|             s1 = -1 if stop=='*' else int(stop)
273|             self.fields.append(slice(s0,s1))
274|         Log.debug(f'{self.fields=}')
275|         Log.debug()
276| 
277|     def __call__ (self, datum):
278|         """Process next chunk of data."""
279|         if datum is None:
280|             self.status = -1
281|             return None
282|         if len(datum) == 0:
283|             return None
284|         super().__call__(datum)
285| 
286|         # Extract specified columns...
287|         buf = []
288|         for ix,field in enumerate(self.fields):
289|             # Insert separator between columns...
290|             if 0 < ix:
291|                 buf.append(ipo_token(self.delim, datum[0].row, 0, SEP_TAG))
292|             # Add field to buffer...
293|             buf.extend(datum[field])
294| 
295|         # Ensure line ends with an EOL...
296|         if len(buf):
297|             if buf[-1]() != EOL:
298|                 buf.append(ipo_token(EOL, 0,0, EOL_TAG))
299| 
300|         # Return extracted tokens...
301|         return buf
302| 
303| 
304| ####################################################################################################
305| if __name__ == '__main__':
306|     print()
307|     ipos = []
308| 
309|     ipos.append(ipo_proc_nop())
310|     ipos.append(None)
311| 
312|     ipos.append(ipo_proc_ascii())
313|     ipos.append(ipo_proc_change())
314|     ipos.append(ipo_proc_rot13())
315|     ipos.append(ipo_proc_tab_2_spc())
316|     ipos.append(None)
317| 
318|     ipos.append(ipo_proc_find())
319|     ipos.append(ipo_proc_regex())
320|     ipos.append(None)
321| 
322|     ipos.append(ipo_proc_fields(**{'cols':'0:99'}))
323|     ipos.append(None)
324| 
325|     for ix,obj in enumerate(ipos):
326|         if obj is None:
327|             print()
328|             continue
329|         print(f'{ix:2d}: {obj!s}')
330|         obj.start(None)
331|     print()
332| ####################################################################################################
333| """eof"""
334|