forked from akkana/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlanggrep
executable file
·79 lines (69 loc) · 2.2 KB
/
langgrep
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
#! /usr/bin/env python
# langgrep: grep for a pattern but only in files written in the
# specified language (as specified by the shebang line).
#
# Copyright 2009 by Akkana Peck.
# Please share, modify and enjoy under the terms of the GPL v2
# or, at your option, any later GPL version.
#
# Bugs: it isn't smart about parsing the grep flags.
# Anything beginning with a - will be considered a flag
# and passed on to grep; the first argument not starting with -
# is taken to be the search pattern, and everything after that
# is the file list.
#
import string, os, sys
import subprocess
import shlex
def Usage():
print "langgrep lang [grepflags] pattern files"
print " e.g. langgrep python -w find *"
sys.exit(0)
def check_file_lang(filename, lang) :
if os.path.isdir(filename) or not os.path.exists(filename) :
return False
try :
f = open(filename)
firstline = f.readline(80)
f.close()
except IOError, e :
print "IOError", e
#print "exc_info is", sys.exc_info()
sys.exit(1)
return False
if firstline[0:2] == "#!" and string.find(firstline, lang) >= 0 :
return True
return False
# main()
if len(sys.argv) < 3 :
Usage()
lang = sys.argv[1]
# After the language, any flag argument plus the grep pattern
# gets appended to args -- these will be the grep args.
patindex = 0
for i in range(2, len(sys.argv)) :
if sys.argv[i][0] != '-' :
patindex = i+1
break
args = sys.argv[2:patindex]
# Now args are the arguments passed to grep;
# the file list, if any, is sys.argv[patindex+1:]
# If no file list, use ~/bin/*
if patindex >= len(sys.argv):
os.chdir(os.path.join(os.getenv("HOME"), "bin"))
files = os.listdir(".")
else :
files = sys.argv[patindex:]
try :
for fil in files :
if check_file_lang(fil, lang) :
#os.system("grep -H" + args + " " + fil)
arglist = ['grep', '-H']
arglist.extend(args)
arglist.append(fil)
subprocess.call(arglist)
# Try to catch ctrl-C and print a nicer message. This doesn't work, though:
# subprocess.call just terminates the whole process.
except KeyboardInterrupt, e :
print "Interrupt!"
sys.exit(1)