Permalink
Browse files

improve result object

  • Loading branch information...
1 parent fbef696 commit 9d7698019365f42dbb97793b4b85e18ca7fd688b @elijahr committed Mar 17, 2012
Showing with 43 additions and 6 deletions.
  1. +43 −6 lk.py
View
@@ -77,7 +77,7 @@ def iterresults(self, paths=None):
with open(path, 'r') as f:
contents = bytearray(f.read())
result = Result(path, contents)
- for match, start, end in self.itermatches(contents):
+ for match in self.itermatches(contents):
result.add(match)
if result.matches:
yield result
@@ -88,25 +88,62 @@ def itermatches(self, string):
start = 0
match = self.regex.search(string, start)
while match:
- yield match, start, match.end()
+ yield match
start = match.end()
match = self.regex.search(string, start)
def iteroutput(self, results=None):
if results is None:
results = self.iterresults()
for result in results:
- yield result
+ yield result.output()
class Result(object):
def __init__(self, path, contents):
self.path = path
- self.contents = contents
self.matches = []
+ self.line_indexes = []
+ start = 0
+ while True:
+ index = contents.find('\n', start)
+ if index < 0:
+ break
+ start += 1
+ self.line_indexes.append(index)
def add(self, match):
- import pdb; pdb.set_trace()
- self.matches.append(match)
+ start = match.start()
+ end = match.end()
+ linenumber = self.get_linenumber(start)
+ lineindex = self.line_indexes[linenumber]
+ nextlineindex = self.line_indexes[linenumber+1]
+ linetext = match.string[lineindex:nextlineindex]
+ charnumber = start - lineindex
+ self.matches.append({
+ 'start': start,
+ 'end': end,
+ 'linenumber': linenumber,
+ 'linetext': linetext,
+ 'text': match.group(0),
+ 'charnumber': charnumber
+ })
+
+ def get_linenumber(self, index):
+ "given an index, find out what line it is on"
+ for linenumber in xrange(len(self.line_indexes)):
+ lineindex = self.line_indexes[linenumber]
+ if index >= lineindex:
+ return linenumber
+
+ def get_lineindex(self, linenumber):
+ "returns the position of the line number"
+ return self.line_indexes[linenumber]
+
+ def output(self):
+ output = self.path
+ for match in self.matches:
+ output += '{linenumber}: {linetext}\n'.format(**match)
+ return output
def create_argparser():
"""

0 comments on commit 9d76980

Please sign in to comment.