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|     ## SCAN FILE
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|         # Scan file...
064|         fp = open(filename, mode='r', encoding='utf-8')
065|         try:
066|             # Scan the file lines...
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|         # Close file...
086|         return n_matches
087| 
088|     ## ===================================================================##
089|     ## SCAN DIRECTORY
090|     ## ===================================================================##
091|     def scanDirectory (self, pathname):
092|         '''Recursive directory scanner.'''
093|         self.info('Directory: %s' % pathname)
094|         t_matches = 0
095| 
096|         # Get a list of filenames in the Search Path...
097|         file_and_dir_names = listdir(pathname)
098|         # Got any files to process?...
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|         # Generate a list of files only...
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|         # Remove names not in the File-Types list...
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|         # Remove names matched by any File-Exclude filter...
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|         # Remove names NOT matched by at least one File-Include filter...
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|         # Got any files left to process?...
128|         if len(fnames):
129|             self.trace('> files-to-scan: %d' % len(fnames))
130|             # Scan Files...
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|         # Scan Sub-Directories (RECURSIVE!)...
141|         if self.recurse_folders:
142|             # Generate a list of sub-directories only...
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|             # Remove names matched by any Path-Exclude filter...
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|             # Remove names NOT matched by at least one Path-Include filter...
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|     ## GREP
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|         # Compile search string into a search object...
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|         # File Include Filters...
186|         for ff in self.file_includes:
187|             fx = compile(ff, RegexFlag.IGNORECASE)
188|             self.file_include_filter.append(fx)
189| 
190|         # File Exclude Filters...
191|         for ff in self.file_excludes:
192|             fx = compile(ff, RegexFlag.IGNORECASE)
193|             self.file_exclude_filter.append(fx)
194| 
195|         # Path Include Filters...
196|         for ff in self.path_includes:
197|             fx = compile(ff, RegexFlag.IGNORECASE)
198|             self.path_include_filter.append(fx)
199| 
200|         # Path Exclude Filters...
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|         # SCAN DIRECTORY...
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|         # This is the only place that uses self.log...
236|         # This and the print_configuration methond both use self.out...
237|         return GrepConfig(name, self.out, self.log)
238| 
239|     def print_configuration (self):
240|         '''Print the current Config object.'''
241|         # Add to the output created by the Config object...
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|         # <Configuration> elements...
262|         if self.state == 100:
263|             # Data elements...
264|             # <SearchExpression> (state: 101<100)...
265|             if name == 'SearchExpression':
266|                 self.state = 101
267|                 return
268|             # <RecurseFolders> (state: 102<100)...
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|             # List elements...
276|             # <FilePaths> (state: 103<100)...
277|             if name == 'FilePaths':
278|                 self.state = 103
279|                 return
280|             # <FileTypes> (state: 104<100)...
281|             if name == 'FileTypes':
282|                 self.state = 104
283|                 return
284|             # <FileIncludePatterns> (state: 105<100)...
285|             if name == 'FileIncludePatterns':
286|                 self.state = 105
287|                 return
288|             # <FileExcludePatterns> (state: 106<100)...
289|             if name == 'FileExcludePatterns':
290|                 self.state = 106
291|                 return
292|             # <PathIncludePatterns> (state: 107<100)...
293|             if name == 'PathIncludePatterns':
294|                 self.state = 107
295|                 return
296|             # <PathExcludePatterns> (state: 108<100)...
297|             if name == 'PathExcludePatterns':
298|                 self.state = 108
299|                 return
300|             return
301|         # List Item elements...
302|         # <FilePath> (state: 113<103)...
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|         # <FileType> (state: 114<104)...
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|         # <FileIncludePattern> (state: 115<105)...
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|         # <FileExcludePattern> (state: 116<106)...
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|         # <PathIncludePattern> (state: 117<107)...
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|         # <PathExcludePattern> (state: 118<108)...
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|         # Let the parent handle any other states...
339|         XmlHandlerConfigBase.localStart(self, name, attrs)
340| 
341|     def localEnd (self, name):
342|         # Data elements...
343|         # <SearchExpression>...
344|         if self.state == 101:
345|             if name == 'SearchExpression':
346|                 self.state = 100
347|                 self.curr_config.search_expression = self.text
348|             return
349|         # <RecurseFolders>...
350|         if self.state == 102:
351|             if name == 'RecurseFolders':
352|                 self.state = 100
353|             return
354|         # List elements...
355|         # <FilePaths>...
356|         if self.state == 103:
357|             if name == 'FilePaths':
358|                 self.state = 100
359|             return
360|         # <FileTypes>...
361|         if self.state == 104:
362|             if name == 'FileTypes':
363|                 self.state = 100
364|             return
365|         # <FileIncludePatterns>...
366|         if self.state == 105:
367|             if name == 'FileIncludePatterns':
368|                 self.state = 100
369|             return
370|         # <FileExcludePatterns>...
371|         if self.state == 106:
372|             if name == 'FileExcludePatterns':
373|                 self.state = 100
374|             return
375|         # <PathIncludePatterns>...
376|         if self.state == 107:
377|             if name == 'PathIncludePatterns':
378|                 self.state = 100
379|             return
380|         # <PathExcludePatterns>...
381|         if self.state == 108:
382|             if name == 'PathExcludePatterns':
383|                 self.state = 100
384|             return
385|         # List Item elements...
386|         # <FilePath>...
387|         if self.state == 113:
388|             if name == 'FilePath':
389|                 self.state = 103
390|             return
391|         # <FileType>...
392|         if self.state == 114:
393|             if name == 'FileType':
394|                 self.state = 104
395|             return
396|         # <FileIncludePattern>...
397|         if self.state == 115:
398|             if name == 'FileIncludePattern':
399|                 self.state = 105
400|             return
401|         # <FileExcludePattern>...
402|         if self.state == 116:
403|             if name == 'FileExcludePattern':
404|                 self.state = 106
405|             return
406|         # <PathIncludePattern>...
407|         if self.state == 117:
408|             if name == 'PathIncludePattern':
409|                 self.state = 107
410|             return
411|         # <PathExcludePattern>...
412|         if self.state == 118:
413|             if name == 'PathExcludePattern':
414|                 self.state = 108
415|             return
416|         # Let the parent handle any other states...
417|         XmlHandlerConfigBase.localEnd(self, name)
418| 
419| 
420| ####################################################################################################
421| '''eof'''
422|