grep.html
001| '''Python GREP implementation.
001|
001| classes:
001| GrepConfig (object)
001| XmlHandlerCfgGrep (XmlHandlerConfigBase)
001|
001| '''
002|
003| from os import path, listdir
004| from re import compile, RegexFlag
005| from xml_sax import XmlHandlerConfigBase
006|
007|
008|
009| class GrepConfig (object):
010| '''GREP Configuration object. Searches a set of (filtered) directories for (filtered files).'''
011|
012| def __init__ (self, name, fout, log=None):
013| '''New GREP Config. (name=identifier, fout=output-file)'''
014| self.name = name
015| self.label = ''
016| self.description = ''
017| self.search_expression = None
018| self.recurse_folders = False
019| self.file_paths = []
020| self.file_types = []
021| self.file_includes = []
022| self.file_excludes = []
023| self.path_includes = []
024| self.path_excludes = []
025| self.search_object = None
026| self.file_include_filter = []
027| self.file_exclude_filter = []
028| self.path_include_filter = []
029| self.path_exclude_filter = []
030| self.no_scan_flag = False
031| self.out = fout
032| self.log = log
033| self.total_matches = 0
034| self.found_files = []
035|
036| def __str__ (self):
037| return self.name
038|
039| def __call__ (self):
040| return self.search_expression
041|
042| def info (self, txt=''):
043| if self.log: self.log.info(txt)
044| def debug (self, txt=''):
045| if self.log: self.log.debug(txt)
046| def trace (self, txt=''):
047| if self.log: self.log.trace(txt)
048| def warn (self, txt=''):
049| if self.log: self.log.warn(txt)
050| def error (self, txt=''):
051| if self.log: self.log.error(txt)
052|
053|
054|
055|
056| def scanFile (self, filename):
057| '''Open a file and scan it for pattern matches.'''
058| n_matches = 0
059| ln = 0
060| virgin = True
061| self.info('File: %s' % filename)
062| if self.no_scan_flag: return 0
063|
064| fp = open(filename, mode='r', encoding='utf-8')
065| try:
066|
067| for txt in fp:
068| txt = txt.strip()
069| ln = ln + 1
070| if self.search_object.search(txt):
071| if virgin:
072| print(filename, file=self.out)
073| virgin = False
074| print('[%d] %s' % (ln, txt), file=self.out)
075| n_matches += 1
076| if not virgin:
077| print(file=self.out)
078|
079| except Exception as e:
080| print(e, file=self.out)
081| self.error(e)
082| raise
083| finally:
084| fp.close()
085|
086| return n_matches
087|
088|
089|
090|
091| def scanDirectory (self, pathname):
092| '''Recursive directory scanner.'''
093| self.info('Directory: %s' % pathname)
094| t_matches = 0
095|
096|
097| file_and_dir_names = listdir(pathname)
098|
099| if len(file_and_dir_names) == 0:
100| self.trace('No files found!')
101| return t_matches
102| self.trace('Directory entries: %d' % len(file_and_dir_names))
103|
104|
105| func = lambda fn: path.isfile(path.join(pathname,fn))
106| fnames = [fn for fn in file_and_dir_names if func(fn)]
107| self.trace('> files-found: %d' % len(fnames))
108|
109|
110| if 0 < len(self.file_types):
111| func = lambda fn: 0 < sum([fn.endswith(ft) for ft in self.file_types])
112| fnames = [fn for fn in fnames if func(fn)]
113| self.trace('> files-after-ftype: %d' % len(fnames))
114|
115|
116| if 0 < len(self.file_exclude_filter):
117| func = lambda fn: 0 == sum([(1 if ff.search(fn) else 0) for ff in self.file_exclude_filter])
118| fnames = [fn for fn in fnames if func(fn)]
119| self.trace('> files-after-exclude: %d' % len(fnames))
120|
121|
122| if 0 < len(self.file_include_filter):
123| func = lambda fn: 0 < sum([(1 if ff.search(fn) else 0) for ff in self.file_include_filter])
124| fnames = [fn for fn in fnames if func(fn)]
125| self.trace('> files-after-include: %d' % len(fnames))
126|
127|
128| if len(fnames):
129| self.trace('> files-to-scan: %d' % len(fnames))
130|
131| for fn in sorted(fnames):
132| filename = path.join (pathname, fn)
133| n = self.scanFile(filename)
134| t_matches += n
135| if 0 < n:
136| self.found_files.append(filename)
137| else:
138| self.trace('No files to Scan!')
139|
140|
141| if self.recurse_folders:
142|
143| dnames = [dn for dn in [path.join(pathname,fn) for fn in file_and_dir_names] if path.isdir(dn)]
144| self.trace('> subdirs-found: %d' % len(dnames))
145|
146|
147| if 0 < len(self.path_exclude_filter):
148| func = lambda fn: 0 == sum([(1 if ff.search(fn) else 0) for ff in self.path_exclude_filter])
149| dnames = [dn for dn in dnames if func(dn)]
150| self.trace('> subdirs-after-exclude: %d' % len(dnames))
151|
152|
153| if 0 < len(self.path_include_filter):
154| func = lambda fn: 0 < sum([(1 if ff.search(fn) else 0) for ff in self.path_include_filter])
155| dnames = [dn for dn in dnames if func(dn)]
156| self.trace('> subdirs-after-include: %d' % len(dnames))
157|
158| if len(dnames):
159| self.debug('> subdirs-to-recurse: %d' % len(dnames))
160| for subdirname in sorted(dnames):
161| n = self.scanDirectory(subdirname)
162| t_matches += n
163|
164| return t_matches
165|
166|
167|
168|
169| def execute (self, search_str=None):
170| '''Execute a search for <search_str>.'''
171| if search_str:
172| self.search_expression = search_str
173|
174| self.info('SEARCH: /%s/' % self.search_expression)
175| for fpath in self.file_paths:
176| self.trace('directory: %s' % fpath)
177| self.debug('recurse? %s' % self.recurse_folders)
178|
179|
180| self.search_object = compile(self.search_expression)
181| self.debug('search-pattern: /%s/' % self.search_object.pattern)
182|
183| print('SEARCH STRING: "%s"' % self.search_expression, file=self.out)
184|
185|
186| for ff in self.file_includes:
187| fx = compile(ff, RegexFlag.IGNORECASE)
188| self.file_include_filter.append(fx)
189|
190|
191| for ff in self.file_excludes:
192| fx = compile(ff, RegexFlag.IGNORECASE)
193| self.file_exclude_filter.append(fx)
194|
195|
196| for ff in self.path_includes:
197| fx = compile(ff, RegexFlag.IGNORECASE)
198| self.path_include_filter.append(fx)
199|
200|
201| for ff in self.path_excludes:
202| fx = compile(ff, RegexFlag.IGNORECASE)
203| self.path_exclude_filter.append(fx)
204|
205| for flt in self.file_include_filter:
206| self.trace('file-include-filter: %s' % flt.pattern)
207| for flt in self.file_exclude_filter:
208| self.trace('file-exclude-filter: %s' % flt.pattern)
209| for flt in self.path_include_filter:
210| self.trace('path-include-filter: %s' % flt.pattern)
211| for flt in self.path_exclude_filter:
212| self.trace('path-exclude-filter: %s' % flt.pattern)
213|
214|
215| print(file=self.out)
216| self.found_files = []
217| self.total_matches = 0
218| for fpath in self.file_paths:
219| n = self.scanDirectory(fpath)
220| self.info('MATCHES: %d' % n)
221| self.total_matches += n
222| self.info('TOTAL-MATCHES: %d' % self.total_matches)
223|
224|
225|
226| class XmlHandlerCfgGrep (XmlHandlerConfigBase):
227| '''XML SAX Handler for GREP Configuration files.'''
228|
229| def __init__ (self, name, fout, log=None):
230| '''New Handler. (name=identifier, fout=output-file)'''
231| XmlHandlerConfigBase.__init__(self, name, fout, log)
232|
233| def new_config_object (self, name):
234| '''Create a new Config object. [required override]'''
235|
236|
237| return GrepConfig(name, self.out, self.log)
238|
239| def print_configuration (self):
240| '''Print the current Config object.'''
241|
242| if self.out and (self.state == 0):
243| print('Configuration: "%s"' % self.curr_config, file=self.out)
244| print('. Search String: "%s"' % self.curr_config.search_expression, file=self.out)
245| print('. Recursive: "%s"' % self.curr_config.recurse_folders, file=self.out)
246| for s in self.curr_config.file_paths:
247| print('. dir "%s"' % s, file=self.out)
248| for s in self.curr_config.file_types:
249| print('. ext "%s"' % s, file=self.out)
250| for s in self.curr_config.file_includes:
251| print('. fin "%s"' % s, file=self.out)
252| for s in self.curr_config.file_excludes:
253| print('. fex "%s"' % s, file=self.out)
254| for s in self.curr_config.path_includes:
255| print('. din "%s"' % s, file=self.out)
256| for s in self.curr_config.path_excludes:
257| print('. dex "%s"' % s, file=self.out)
258| print(file=self.out)
259|
260| def localStart (self, name, attrs):
261|
262| if self.state == 100:
263|
264|
265| if name == 'SearchExpression':
266| self.state = 101
267| return
268|
269| if name == 'RecurseFolders':
270| self.state = 102
271| s = self.get_attribute(attrs, 'value')
272| x = s in ['1', 'T','t' 'True','true', 'Y','y', 'Yes','yes', 'Yep','yep','On', 'Enable','enable', 'GO FOR IT','go for it']
273| self.curr_config.recurse_folders = x
274| return
275|
276|
277| if name == 'FilePaths':
278| self.state = 103
279| return
280|
281| if name == 'FileTypes':
282| self.state = 104
283| return
284|
285| if name == 'FileIncludePatterns':
286| self.state = 105
287| return
288|
289| if name == 'FileExcludePatterns':
290| self.state = 106
291| return
292|
293| if name == 'PathIncludePatterns':
294| self.state = 107
295| return
296|
297| if name == 'PathExcludePatterns':
298| self.state = 108
299| return
300| return
301|
302|
303| if self.state == 103:
304| if name == 'FilePath':
305| self.state = 113
306| self.curr_config.file_paths.append(self.get_attribute(attrs,'folder'))
307| return
308|
309| if self.state == 104:
310| if name == 'FileType':
311| self.state = 114
312| self.curr_config.file_types.append(self.get_attribute(attrs,'ext'))
313| return
314|
315| if self.state == 105:
316| if name == 'FileIncludePattern':
317| self.state = 115
318| self.curr_config.file_includes.append(self.get_attribute(attrs,'match'))
319| return
320|
321| if self.state == 106:
322| if name == 'FileExcludePattern':
323| self.state = 116
324| self.curr_config.file_excludes.append(self.get_attribute(attrs,'match'))
325| return
326|
327| if self.state == 107:
328| if name == 'PathIncludePattern':
329| self.state = 117
330| self.curr_config.path_includes.append(self.get_attribute(attrs,'match'))
331| return
332|
333| if self.state == 108:
334| if name == 'PathExcludePattern':
335| self.state = 118
336| self.curr_config.path_excludes.append(self.get_attribute(attrs,'match'))
337| return
338|
339| XmlHandlerConfigBase.localStart(self, name, attrs)
340|
341| def localEnd (self, name):
342|
343|
344| if self.state == 101:
345| if name == 'SearchExpression':
346| self.state = 100
347| self.curr_config.search_expression = self.text
348| return
349|
350| if self.state == 102:
351| if name == 'RecurseFolders':
352| self.state = 100
353| return
354|
355|
356| if self.state == 103:
357| if name == 'FilePaths':
358| self.state = 100
359| return
360|
361| if self.state == 104:
362| if name == 'FileTypes':
363| self.state = 100
364| return
365|
366| if self.state == 105:
367| if name == 'FileIncludePatterns':
368| self.state = 100
369| return
370|
371| if self.state == 106:
372| if name == 'FileExcludePatterns':
373| self.state = 100
374| return
375|
376| if self.state == 107:
377| if name == 'PathIncludePatterns':
378| self.state = 100
379| return
380|
381| if self.state == 108:
382| if name == 'PathExcludePatterns':
383| self.state = 100
384| return
385|
386|
387| if self.state == 113:
388| if name == 'FilePath':
389| self.state = 103
390| return
391|
392| if self.state == 114:
393| if name == 'FileType':
394| self.state = 104
395| return
396|
397| if self.state == 115:
398| if name == 'FileIncludePattern':
399| self.state = 105
400| return
401|
402| if self.state == 116:
403| if name == 'FileExcludePattern':
404| self.state = 106
405| return
406|
407| if self.state == 117:
408| if name == 'PathIncludePattern':
409| self.state = 107
410| return
411|
412| if self.state == 118:
413| if name == 'PathExcludePattern':
414| self.state = 108
415| return
416|
417| XmlHandlerConfigBase.localEnd(self, name)
418|
419|
420|
421| '''eof'''
422|