Debian Codegraph @

tools/search.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 ##--------------------------------------##
5 # WxGeometrie #
6 # Global search utility #
7 ##--------------------------------------##
8 # WxGeometrie
9 # Dynamic geometry, graph plotter, and more for french mathematic teachers.
10 # Copyright (C) 2005-2013 Nicolas Pourcelot
11 #
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
16 #
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
21 #
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26
27 import os
28 import sys
29 import re
30 import subprocess
31 import argparse
32
33 # ----- User config -----
34 IGNORE = ('*tmp_*', '*(OLD|BAZAR)*', '*sympy/*', '*modules/traceur/tableau.py',
35 '*/(pyshell|idle).pyw', '*/rpdb2.py')
36 DEFAULT_EDITOR = 'geany'
37 # XXX: move this outside the script
38 # ------------------------
39
40 #TODO: provide default IGNORE by autodetecting .gitignore content, if any.
41
42 SUPPORTED_EDITORS = ('geany', 'gedit', 'nano', 'vim', 'emacs', 'kate', 'kile')
43
44 def gs(string='', case=True, include_comments=False, comment_marker='#', extensions=(".py", ".pyw"),
45 maximum=100, codec="utf8", stats=False, replace_with=None,
46 color=None, edit_with=None, edit_result=None, skip_paths=()):
47 """Parcourt le répertoire courant et les sous-répertoire, à la recherche
48 des fichiers dont l'extension est comprise dans 'extensions',
49 mais passe les répertoires et les fichiers dont le nom commence par
50 un préfixe de 'exclude_prefixe', ou finit par un suffixe de
51 'exclude_suffixe'.
52 Pour chaque fichier trouvé, renvoie toutes les lignes où 'string' se trouve.
53 (Par défaut, la casse est prise en compte, sinon, il suffit de modifier
54 la valeur de 'case'.)
55 Le nombre maximal de lignes renvoyées est fixé par 'maximum', afin d'éviter
56 de saturer le système.
57 Si ce nombre est dépassé (ie. toutes les occurences de 'string' ne sont pas
58 affichées), la fonction renvoie False, sinon, True.
59 """
60
61 if skip_paths:
62 IGNORE_RE = re.compile('|'.join('(%s)' % pattern.replace('*', '.*').strip()
63 for pattern in skip_paths if pattern))
64 else:
65 IGNORE_RE = None
66
67
68 if color is None:
69 color = sys.platform.startswith('linux')
70 if color:
71 def blue(s):
72 return '\033[0;36m' + s + '\033[0m'
73 def blue2(s):
74 return '\033[1;36m' + s + '\033[0m'
75 def red(s):
76 return '\033[0;31m' + s + '\033[0m'
77 def green(s):
78 return '\033[0;32m' + s + '\033[0m'
79 def green2(s):
80 return '\033[1;32m' + s + '\033[0m'
81 def yellow(s):
82 return '\033[0;33m' + s + '\033[0m'
83 def white(s):
84 return '\033[1;37m' + s + '\033[0m'
85 else:
86 green = blue = white = blue2 = red = green2 = yellow = (lambda s:s)
87
88 if not string:
89 stats = True
90 if not case:
91 string = string.lower()
92 if replace_with is not None:
93 assert case
94 cwd = os.getcwd()
95 repertoires = os.walk(cwd)
96 print ("Searching in " + green(cwd) + "...")
97 end_root_pos = len(cwd) + 1
98 print('')
99 fichiers = []
100 for root, dirs, files in repertoires:
101 files = [f for f in files if f[f.rfind("."):] in extensions]
102 fichiers += [root + os.sep + f for f in files]
103 # nombre de lignes de code au total
104 N = 0
105 # nombre de lignes de commentaires au total
106 C = 0
107 # nombre de fichiers
108 F = 0
109 # nombre de lignes vides
110 B = 0
111 # nombre de lignes contenant l'expression recherchée
112 n_lignes = 0
113 # Nombre d'occurences trouvées.
114 occurences = 0
115 for filename in fichiers:
116 if IGNORE_RE is not None and re.search(IGNORE_RE, filename):
117 continue
118 F += 1
119 correct_encoding = True
120 with open(filename) as fichier:
121 lignes = []
122 results = []
123 try:
124 for n, s in enumerate(fichier):
125 if replace_with is not None:
126 lignes.append(s)
127 if stats:
128 s = s.strip()
129 if s:
130 if s[0] != comment_marker:
131 N += 1
132 elif s.strip(comment_marker):
133 C += 1
134 else:
135 B += 1
136 else:
137 B += 1
138 continue
139 if not include_comments and s.lstrip().startswith(comment_marker):
140 # comment line
141 continue
142 if not case:
143 s = s.lower()
144 pos = s.find(string)
145 if pos != -1:
146 if not include_comments:
147 substr = s[:pos]
148 if comment_marker in substr:
149 # test if the substring found was inside a comment
150 # at the end of the line.
151 # You have to be carefull, because `comment_marker` may be
152 # inside a string...
153 # TODO: handle triple quotes.
154 mode = None
155 for c in substr:
156 if c in ("'", '"', comment_marker):
157 if mode is None:
158 mode = c
159 if c == comment_marker:
160 continue
161 elif mode == c:
162 mode = None
163 if mode == comment_marker:
164 # substring found inside a comment
165 continue
166
167 occurences += 1
168 if replace_with is not None:
169 lignes[-1] = s.replace(string, replace_with)
170 s = s[:pos] + blue2(s[pos:pos+len(string)]) \
171 + s[pos+len(string):]
172 results.append(" " + blue('(' + str(n_lignes + 1) + ')')
173 + " line " + white(str(n + 1))
174 + ": " + s)
175
176 if edit_with is not None and edit_result is not None and (len(edit_result) == 0
177 or ((n_lignes + 1) in edit_result)):
178 if edit_with not in SUPPORTED_EDITORS:
179 print(edit_with + ' is currently not supported.')
180 print('Supported editors : '
181 + ','.join(SUPPORTED_EDITORS))
182 elif edit_with in ('geany', 'kate'):
183 command = '%s -l %s %s' % (edit_with, n + 1, filename)
184 elif edit_with in ('kile',):
185 command = '%s --line %s %s' % (edit_with, n + 1, filename)
186 else:
187 command = '%s +%s %s' % (edit_with, n + 1, filename)
188 #~ print('%s executed...' % command)
189 subprocess.call(command, shell=True)
190
191 n_lignes += 1
192 if n_lignes > maximum:
193 return red("Maximum output exceeded...!")
194 except UnicodeDecodeError:
195 correct_encoding = False
196 print(red("ERROR:") + " Can't read %s, encoding isn't %s."
197 % (filename, sys.getdefaultencoding()))
198
199 if correct_encoding and results:
200 print(" \u2022 in " + green(filename[:end_root_pos])
201 + green2(filename[end_root_pos:]))
202 for result in results:
203 print(result.rstrip())
204
205 if replace_with is not None:
206 with open(filename, 'w') as fichier:
207 for l in lignes:
208 fichier.write(l)
209
210 if stats:
211 # C - 20*F : on décompte les préambules de tous les fichiers
212 return (blue(str(N) + " lignes de code\n")
213 + str(C) + " lignes de commentaires (" + str(C - 20*F)
214 + " hors licence)\n"
215 + str(B) + " lignes vides\n"
216 + str(F) + " fichiers")
217 if replace_with is None:
218 return blue("\n-> %s occurence(s) trouvée(s)." % occurences)
219 else:
220 return blue("%s occurence(s) de %s remplacée(s) par %s."
221 % (occurences, repr(string), repr(replace_with)))
222
223
224
225 if __name__ == "__main__":
226 parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS,
227 description='Search recursively for specified string in all the files of a directory.')
228 parser.add_argument('string', metavar='STRING', help='string to search')
229 parser.add_argument('-r', '--replace-with', metavar='REPLACEMENT_STRING',
230 help='Replace all occurrences of STRING with REPLACEMENT_STRING.')
231 parser.add_argument('-e', '--edit-result', metavar='N', type=int, nargs='*',
232 help='''Open editor and display result number N
233 (use --edit with no argument to
234 open all files where searched string was found).''')
235 parser.add_argument('-w', '--edit-with', metavar='EDITOR',
236 choices=SUPPORTED_EDITORS, default=DEFAULT_EDITOR)
237 parser.add_argument('-s', '--stats', help='Display statistics concerning scanned files.')
238 parser.add_argument('-m', '--maximum', type=int, metavar='N', default=100,
239 help='Display only the first N results.')
240 parser.add_argument('-i', '--include-comments', action='store_true',
241 help='Search in comments too.')
242 parser.add_argument('-x', '--extensions', metavar='EXTENSION', nargs='+',
243 default=('.py', '.pyw'),
244 help='Search only files whose name ends with any specified extension.')
245 parser.add_argument('-n', '--no-color', dest='color', action='store_false',
246 help='Disable colors.')
247 parser.add_argument('-k', '--skip-paths', metavar='PATH_TO_SKIP', nargs='*',
248 default=IGNORE, help='Paths to skip.')
249 parser.add_argument('-c', '--discard-case', dest='case', action='store_false',
250 help='Make search case insensitive.')
251 args = parser.parse_args()
252
253 title = "\n=== Recherche de %s ===\n" % repr(args.string)
254 if sys.platform.startswith('linux'):
255 title = '\033[1;37m' + title + '\033[0m'
256 print(title)
257 #~ print(vars(args))
258 print(gs(**vars(args)))