-
Notifications
You must be signed in to change notification settings - Fork 20
/
sniff.py
executable file
·105 lines (87 loc) · 2.46 KB
/
sniff.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env python
import os
import sys
import re
# Definitions of colors in bash
RESTORE = "\033[0m"
RED = "\033[00;31m"
class Match:
def __init__(self):
self.path = None
self.filename = None
self.lines = list()
self.matchIndex = 0.0
self.nos = 0
def __str__(self):
for i in range(len(self.lines)):
if i == 0:
pass
else:
self.lines[i] = self.lines[i - 1] + self.lines[i] - 1
# Last entry is not the position of match. remove it
self.lines.pop()
txt = RED + self.path + RESTORE + ":"
for l in self.lines:
txt += "{} ".format(l)
return txt
def __repr__(self):
return self.__str__()
files = set()
result = list()
def insertIntoResult(match):
global result
i = 0
if len(result) == 0:
result.append(match)
return
for r in result:
if match.matchIndex > r.matchIndex:
result.insert(i, match)
return
else:
i += 1
result.append(match)
def filter(pat):
global files
# Do some intelligent stuff with pattern
# 1. if space is given in pattern replace it with \s+
pat = re.sub("\s+", "\s+", pat)
pat = re.compile(pat, re.DOTALL)
for ff in files:
with open(ff, "r") as f:
txt = f.read()
l = pat.split(txt)
if len(l) > 1:
lines = []
for i in l:
lines.append(len(i.split("\n")))
match = Match()
match.path = ff
match.filename = os.path.basename(ff)
match.lines = lines
match.matchIndex = match.nos
insertIntoResult(match)
def main(pat, filepat):
global files
global result
dir, _ = os.path.dirname(pat), os.path.basename(pat)
if "**" in dir:
dir = dir.split("**")[0]
for d, ds, fs in os.walk(dir):
for f in fs:
filename = os.path.join(d, f)
if re.match(filepat, filename):
files.add(filename)
filter(pat)
for r in result:
print(r)
if __name__ == "__main__":
if len(sys.argv) < 3:
print("USAGE: {0} text_to_find_pattern [file_pattern]".format(sys.argv[0]))
sys.exit(0)
pattern = sys.argv[1]
if len(sys.argv) > 2:
filepattern = sys.argv[2]
else:
filepattern = ".+"
main(pattern, filepattern)