Created
February 7, 2009 16:53
-
-
Save jqr/59936 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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