Skip to content

Instantly share code, notes, and snippets.

@jqr
Created February 7, 2009 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jqr/59936 to your computer and use it in GitHub Desktop.
Save jqr/59936 to your computer and use it in GitHub Desktop.
import os, re
class CachedFileSearch(object):
"""Cached File Search"""
def __init__(self, dir):
self.dir = dir
self.all_files = os.popen('find ' + dir).read()
self.clear_cache()
def search(self, pattern):
if pattern:
if pattern in self.cached_results:
matches = self.cached_results[pattern]
else:
partial_match_pattern = self.find_partial_match_pattern(pattern)
if partial_match_pattern:
scope = self.search(partial_match_pattern)
else:
scope = self.all_files
matches = "\n".join(re.findall('.*' + pattern + '.*', scope))
self.cached_results[pattern] = matches
return matches
def find_partial_match_pattern(self, pattern):
for cached_pattern in self.cached_patterns():
if re.match('^' + cached_pattern, pattern):
return(cached_pattern)
def clear_cache(self):
self.cached_results = {}
def cached_patterns(self):
return self.cached_results.keys()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment