Debian Codegraph @

Cheetah/FileUtils.py

raw symbols SCIP
1
2 from glob import glob
3 import os
4 import os.path
5 import re
6 from tempfile import NamedTemporaryFile
7 from .compat import string_type
8
9
10 def _escapeRegexChars(
11 txt, escapeRE=re.compile(r'([\$\^\*\+\.\?\{\}\[\]\(\)\|\\])')):
12 return escapeRE.sub(r'\\\1', txt)
13
14
15 def findFiles(*args, **kw):
16 """Recursively find all the files matching a glob pattern.
17
18 This function is a wrapper around the FileFinder class. See its docstring
19 for details about the accepted arguments, etc."""
20
21 return FileFinder(*args, **kw).files()
22
23
24 def replaceStrInFiles(files, theStr, repl):
25
26 """
27 Replace all instances of 'theStr' with 'repl' for each file in the 'files'
28 list. Returns a dictionary with data about the matches found.
29
30 This is like string.replace() on a multi-file basis.
31
32 This function is a wrapper around the FindAndReplace class. See its
33 docstring for more details.
34 """
35
36 pattern = _escapeRegexChars(theStr)
37 return FindAndReplace(files, pattern, repl).results()
38
39
40 def replaceRegexInFiles(files, pattern, repl):
41 """
42 Replace all instances of regex 'pattern' with 'repl' for each file in the
43 'files' list. Returns a dictionary with data about the matches found.
44
45 This is like re.sub on a multi-file basis.
46
47 This function is a wrapper around the FindAndReplace class. See its
48 docstring for more details.
49 """
50
51 return FindAndReplace(files, pattern, repl).results()
52
53
54 ##################################################
55 # CLASSES
56
57 class FileFinder:
58
59 """Traverses a directory tree and finds all files in it that match one of
60 the specified glob patterns."""
61
62 def __init__(self, rootPath,
63 globPatterns=('*',),
64 ignoreBasenames=('CVS', '.svn'),
65 ignoreDirs=(),
66 ):
67
68 self._rootPath = rootPath
69 self._globPatterns = globPatterns
70 self._ignoreBasenames = ignoreBasenames
71 self._ignoreDirs = ignoreDirs
72 self._files = []
73
74 self.walkDirTree(rootPath)
75
76 def walkDirTree(self, dir='.',
77
78 listdir=os.listdir,
79 isdir=os.path.isdir,
80 join=os.path.join,
81 ):
82
83 """Recursively walk through a directory tree and find matching files"""
84 processDir = self.processDir
85 filterDir = self.filterDir
86
87 pendingDirs = [dir]
88 addDir = pendingDirs.append
89 getDir = pendingDirs.pop
90
91 while pendingDirs:
92 dir = getDir()
93 # process this dir
94 processDir(dir)
95
96 # and add sub-dirs
97 for baseName in listdir(dir):
98 fullPath = join(dir, baseName)
99 if isdir(fullPath):
100 if filterDir(baseName, fullPath):
101 addDir(fullPath)
102
103 def filterDir(self, baseName, fullPath):
104
105 """A hook for filtering out certain dirs. """
106
107 return not (baseName in self._ignoreBasenames
108 or fullPath in self._ignoreDirs)
109
110 def processDir(self, dir, glob=glob):
111 extend = self._files.extend
112 for pattern in self._globPatterns:
113 extend(glob(os.path.join(dir, pattern)))
114
115 def files(self):
116 return self._files
117
118
119 class _GenSubberFunc:
120
121 """Converts a 'sub' string in the form that one feeds to re.sub (backrefs,
122 groups, etc.) into a function that can be used to do the substitutions in
123 the FindAndReplace class."""
124
125 backrefRE = re.compile(r'\\([1-9][0-9]*)')
126 groupRE = re.compile(r'\\g<([a-zA-Z_][a-zA-Z_]*)>')
127
128 def __init__(self, replaceStr):
129 self._src = replaceStr
130 self._pos = 0
131 self._codeChunks = []
132 self.parse()
133
134 def src(self):
135 return self._src
136
137 def pos(self):
138 return self._pos
139
140 def setPos(self, pos):
141 self._pos = pos
142
143 def atEnd(self):
144 return self._pos >= len(self._src)
145
146 def advance(self, offset=1):
147 self._pos += offset
148
149 def readTo(self, to, start=None):
150 if start is None:
151 start = self._pos
152 self._pos = to
153 if self.atEnd():
154 return self._src[start:]
155 else:
156 return self._src[start:to]
157
158 # match and get methods
159
160 def matchBackref(self):
161 return self.backrefRE.match(self.src(), self.pos())
162
163 def getBackref(self):
164 m = self.matchBackref()
165 self.setPos(m.end())
166 return m.group(1)
167
168 def matchGroup(self):
169 return self.groupRE.match(self.src(), self.pos())
170
171 def getGroup(self):
172 m = self.matchGroup()
173 self.setPos(m.end())
174 return m.group(1)
175
176 # main parse loop and the eat methods
177
178 def parse(self):
179 while not self.atEnd():
180 if self.matchBackref():
181 self.eatBackref()
182 elif self.matchGroup():
183 self.eatGroup()
184 else:
185 self.eatStrConst()
186
187 def eatStrConst(self):
188 startPos = self.pos()
189 while not self.atEnd():
190 if self.matchBackref() or self.matchGroup():
191 break
192 else:
193 self.advance()
194 strConst = self.readTo(self.pos(), start=startPos)
195 self.addChunk(repr(strConst))
196
197 def eatBackref(self):
198 self.addChunk('m.group(' + self.getBackref() + ')')
199
200 def eatGroup(self):
201 self.addChunk('m.group("' + self.getGroup() + '")')
202
203 def addChunk(self, chunk):
204 self._codeChunks.append(chunk)
205
206 # code wrapping methods
207
208 def codeBody(self):
209 return ', '.join(self._codeChunks)
210
211 def code(self):
212 return "def subber(m):\n\treturn ''.join([%s])\n" % (self.codeBody())
213
214 def subberFunc(self):
215 exec(self.code())
216 return subber # noqa: F821 undefined name 'subber'
217
218
219 class FindAndReplace:
220
221 """Find and replace all instances of 'patternOrRE' with 'replacement' for
222 each file in the 'files' list. This is a multi-file version of re.sub().
223
224 'patternOrRE' can be a raw regex pattern or
225 a regex object as generated by the re module. 'replacement' can be any
226 string that would work with patternOrRE.sub(replacement, fileContents).
227 """
228
229 def __init__(self, files, patternOrRE, replacement,
230 recordResults=True):
231
232 if isinstance(patternOrRE, string_type):
233 self._regex = re.compile(patternOrRE)
234 else:
235 self._regex = patternOrRE
236 if isinstance(replacement, string_type):
237 self._subber = _GenSubberFunc(replacement).subberFunc()
238 else:
239 self._subber = replacement
240
241 self._pattern = pattern = self._regex.pattern
242 self._files = files
243 self._results = {}
244 self._recordResults = recordResults
245
246 # see if we should use pgrep to do the file matching
247 self._usePgrep = False
248 if (os.popen3('pgrep')[2].read()).startswith('Usage:'):
249 # now check to make sure pgrep understands the pattern
250 tmpFile = NamedTemporaryFile()
251 tmpFile.write('#')
252 if not (os.popen3(
253 'pgrep "' + pattern + '" ' + tmpFile.name)[2].read()):
254 # it didn't print an error msg so we're ok
255 self._usePgrep = True
256 tmpFile.close() # Will be automatically removed on close
257
258 self._run()
259
260 def results(self):
261 return self._results
262
263 def _run(self):
264 regex = self._regex
265 subber = self._subDispatcher
266 usePgrep = self._usePgrep
267 pattern = self._pattern
268 for file in self._files:
269 if not os.path.isfile(file):
270 continue # skip dirs etc.
271
272 self._currFile = file
273 found = False
274 if 'orig' in locals():
275 del orig
276 if self._usePgrep:
277 if os.popen('pgrep "' + pattern + '" ' + file).read():
278 found = True
279 else:
280 orig = open(file).read()
281 if regex.search(orig):
282 found = True
283 if found:
284 if 'orig' not in locals():
285 orig = open(file).read()
286 new = regex.sub(subber, orig)
287 open(file, 'w').write(new)
288
289 def _subDispatcher(self, match):
290 if self._recordResults:
291 if self._currFile not in self._results:
292 res = self._results[self._currFile] = {}
293 res['count'] = 0
294 res['matches'] = []
295 else:
296 res = self._results[self._currFile]
297 res['count'] += 1
298 res['matches'].append({'contents': match.group(),
299 'start': match.start(),
300 'end': match.end(),
301 }
302 )
303 return self._subber(match)
304
305
306 class SourceFileStats:
307
308 """
309 """
310
311 _fileStats = None
312
313 def __init__(self, files):
314 self._fileStats = stats = {}
315 for file in files:
316 stats[file] = self.getFileStats(file)
317
318 def rawStats(self):
319 return self._fileStats
320
321 def summary(self):
322 codeLines = 0
323 blankLines = 0
324 commentLines = 0
325 totalLines = 0
326 for fileStats in self.rawStats().values():
327 codeLines += fileStats['codeLines']
328 blankLines += fileStats['blankLines']
329 commentLines += fileStats['commentLines']
330 totalLines += fileStats['totalLines']
331
332 stats = {'codeLines': codeLines,
333 'blankLines': blankLines,
334 'commentLines': commentLines,
335 'totalLines': totalLines,
336 }
337 return stats
338
339 def printStats(self):
340 pass
341
342 def getFileStats(self, fileName):
343 codeLines = 0
344 blankLines = 0
345 commentLines = 0
346 commentLineRe = re.compile(r'\s#.*$')
347 blankLineRe = re.compile(r'\s$')
348 lines = open(fileName).read().splitlines()
349 totalLines = len(lines)
350
351 for line in lines:
352 if commentLineRe.match(line):
353 commentLines += 1
354 elif blankLineRe.match(line):
355 blankLines += 1
356 else:
357 codeLines += 1
358
359 stats = {'codeLines': codeLines,
360 'blankLines': blankLines,
361 'commentLines': commentLines,
362 'totalLines': totalLines,
363 }
364
365 return stats