ยปCore Development>Code coverage>Tools/scripts/pindent.py

Python code coverage for Tools/scripts/pindent.py

#countcontent
1n/a#! /usr/bin/env python
2n/a
3n/a# This file contains a class and a main program that perform three
4n/a# related (though complimentary) formatting operations on Python
5n/a# programs. When called as "pindent -c", it takes a valid Python
6n/a# program as input and outputs a version augmented with block-closing
7n/a# comments. When called as "pindent -d", it assumes its input is a
8n/a# Python program with block-closing comments and outputs a commentless
9n/a# version. When called as "pindent -r" it assumes its input is a
10n/a# Python program with block-closing comments but with its indentation
11n/a# messed up, and outputs a properly indented version.
12n/a
13n/a# A "block-closing comment" is a comment of the form '# end <keyword>'
14n/a# where <keyword> is the keyword that opened the block. If the
15n/a# opening keyword is 'def' or 'class', the function or class name may
16n/a# be repeated in the block-closing comment as well. Here is an
17n/a# example of a program fully augmented with block-closing comments:
18n/a
19n/a# def foobar(a, b):
20n/a# if a == b:
21n/a# a = a+1
22n/a# elif a < b:
23n/a# b = b-1
24n/a# if b > a: a = a-1
25n/a# # end if
26n/a# else:
27n/a# print 'oops!'
28n/a# # end if
29n/a# # end def foobar
30n/a
31n/a# Note that only the last part of an if...elif...else... block needs a
32n/a# block-closing comment; the same is true for other compound
33n/a# statements (e.g. try...except). Also note that "short-form" blocks
34n/a# like the second 'if' in the example must be closed as well;
35n/a# otherwise the 'else' in the example would be ambiguous (remember
36n/a# that indentation is not significant when interpreting block-closing
37n/a# comments).
38n/a
39n/a# The operations are idempotent (i.e. applied to their own output
40n/a# they yield an identical result). Running first "pindent -c" and
41n/a# then "pindent -r" on a valid Python program produces a program that
42n/a# is semantically identical to the input (though its indentation may
43n/a# be different). Running "pindent -e" on that output produces a
44n/a# program that only differs from the original in indentation.
45n/a
46n/a# Other options:
47n/a# -s stepsize: set the indentation step size (default 8)
48n/a# -t tabsize : set the number of spaces a tab character is worth (default 8)
49n/a# -e : expand TABs into spaces
50n/a# file ... : input file(s) (default standard input)
51n/a# The results always go to standard output
52n/a
53n/a# Caveats:
54n/a# - comments ending in a backslash will be mistaken for continued lines
55n/a# - continuations using backslash are always left unchanged
56n/a# - continuations inside parentheses are not extra indented by -r
57n/a# but must be indented for -c to work correctly (this breaks
58n/a# idempotency!)
59n/a# - continued lines inside triple-quoted strings are totally garbled
60n/a
61n/a# Secret feature:
62n/a# - On input, a block may also be closed with an "end statement" --
63n/a# this is a block-closing comment without the '#' sign.
64n/a
65n/a# Possible improvements:
66n/a# - check syntax based on transitions in 'next' table
67n/a# - better error reporting
68n/a# - better error recovery
69n/a# - check identifier after class/def
70n/a
71n/a# The following wishes need a more complete tokenization of the source:
72n/a# - Don't get fooled by comments ending in backslash
73n/a# - reindent continuation lines indicated by backslash
74n/a# - handle continuation lines inside parentheses/braces/brackets
75n/a# - handle triple quoted strings spanning lines
76n/a# - realign comments
77n/a# - optionally do much more thorough reformatting, a la C indent
78n/a
79n/a# Defaults
80n/aSTEPSIZE = 8
81n/aTABSIZE = 8
82n/aEXPANDTABS = 0
83n/a
84n/aimport re
85n/aimport sys
86n/a
87n/anext = {}
88n/anext['if'] = next['elif'] = 'elif', 'else', 'end'
89n/anext['while'] = next['for'] = 'else', 'end'
90n/anext['try'] = 'except', 'finally'
91n/anext['except'] = 'except', 'else', 'finally', 'end'
92n/anext['else'] = next['finally'] = next['def'] = next['class'] = 'end'
93n/anext['end'] = ()
94n/astart = 'if', 'while', 'for', 'try', 'with', 'def', 'class'
95n/a
96n/aclass PythonIndenter:
97n/a
98n/a def __init__(self, fpi = sys.stdin, fpo = sys.stdout,
99n/a indentsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
100n/a self.fpi = fpi
101n/a self.fpo = fpo
102n/a self.indentsize = indentsize
103n/a self.tabsize = tabsize
104n/a self.lineno = 0
105n/a self.expandtabs = expandtabs
106n/a self._write = fpo.write
107n/a self.kwprog = re.compile(
108n/a r'^\s*(?P<kw>[a-z]+)'
109n/a r'(\s+(?P<id>[a-zA-Z_]\w*))?'
110n/a r'[^\w]')
111n/a self.endprog = re.compile(
112n/a r'^\s*#?\s*end\s+(?P<kw>[a-z]+)'
113n/a r'(\s+(?P<id>[a-zA-Z_]\w*))?'
114n/a r'[^\w]')
115n/a self.wsprog = re.compile(r'^[ \t]*')
116n/a # end def __init__
117n/a
118n/a def write(self, line):
119n/a if self.expandtabs:
120n/a self._write(line.expandtabs(self.tabsize))
121n/a else:
122n/a self._write(line)
123n/a # end if
124n/a # end def write
125n/a
126n/a def readline(self):
127n/a line = self.fpi.readline()
128n/a if line: self.lineno = self.lineno + 1
129n/a # end if
130n/a return line
131n/a # end def readline
132n/a
133n/a def error(self, fmt, *args):
134n/a if args: fmt = fmt % args
135n/a # end if
136n/a sys.stderr.write('Error at line %d: %s\n' % (self.lineno, fmt))
137n/a self.write('### %s ###\n' % fmt)
138n/a # end def error
139n/a
140n/a def getline(self):
141n/a line = self.readline()
142n/a while line[-2:] == '\\\n':
143n/a line2 = self.readline()
144n/a if not line2: break
145n/a # end if
146n/a line = line + line2
147n/a # end while
148n/a return line
149n/a # end def getline
150n/a
151n/a def putline(self, line, indent = None):
152n/a if indent is None:
153n/a self.write(line)
154n/a return
155n/a # end if
156n/a tabs, spaces = divmod(indent*self.indentsize, self.tabsize)
157n/a i = 0
158n/a m = self.wsprog.match(line)
159n/a if m: i = m.end()
160n/a # end if
161n/a self.write('\t'*tabs + ' '*spaces + line[i:])
162n/a # end def putline
163n/a
164n/a def reformat(self):
165n/a stack = []
166n/a while 1:
167n/a line = self.getline()
168n/a if not line: break # EOF
169n/a # end if
170n/a m = self.endprog.match(line)
171n/a if m:
172n/a kw = 'end'
173n/a kw2 = m.group('kw')
174n/a if not stack:
175n/a self.error('unexpected end')
176n/a elif stack[-1][0] != kw2:
177n/a self.error('unmatched end')
178n/a # end if
179n/a del stack[-1:]
180n/a self.putline(line, len(stack))
181n/a continue
182n/a # end if
183n/a m = self.kwprog.match(line)
184n/a if m:
185n/a kw = m.group('kw')
186n/a if kw in start:
187n/a self.putline(line, len(stack))
188n/a stack.append((kw, kw))
189n/a continue
190n/a # end if
191n/a if next.has_key(kw) and stack:
192n/a self.putline(line, len(stack)-1)
193n/a kwa, kwb = stack[-1]
194n/a stack[-1] = kwa, kw
195n/a continue
196n/a # end if
197n/a # end if
198n/a self.putline(line, len(stack))
199n/a # end while
200n/a if stack:
201n/a self.error('unterminated keywords')
202n/a for kwa, kwb in stack:
203n/a self.write('\t%s\n' % kwa)
204n/a # end for
205n/a # end if
206n/a # end def reformat
207n/a
208n/a def delete(self):
209n/a begin_counter = 0
210n/a end_counter = 0
211n/a while 1:
212n/a line = self.getline()
213n/a if not line: break # EOF
214n/a # end if
215n/a m = self.endprog.match(line)
216n/a if m:
217n/a end_counter = end_counter + 1
218n/a continue
219n/a # end if
220n/a m = self.kwprog.match(line)
221n/a if m:
222n/a kw = m.group('kw')
223n/a if kw in start:
224n/a begin_counter = begin_counter + 1
225n/a # end if
226n/a # end if
227n/a self.putline(line)
228n/a # end while
229n/a if begin_counter - end_counter < 0:
230n/a sys.stderr.write('Warning: input contained more end tags than expected\n')
231n/a elif begin_counter - end_counter > 0:
232n/a sys.stderr.write('Warning: input contained less end tags than expected\n')
233n/a # end if
234n/a # end def delete
235n/a
236n/a def complete(self):
237n/a self.indentsize = 1
238n/a stack = []
239n/a todo = []
240n/a thisid = ''
241n/a current, firstkw, lastkw, topid = 0, '', '', ''
242n/a while 1:
243n/a line = self.getline()
244n/a i = 0
245n/a m = self.wsprog.match(line)
246n/a if m: i = m.end()
247n/a # end if
248n/a m = self.endprog.match(line)
249n/a if m:
250n/a thiskw = 'end'
251n/a endkw = m.group('kw')
252n/a thisid = m.group('id')
253n/a else:
254n/a m = self.kwprog.match(line)
255n/a if m:
256n/a thiskw = m.group('kw')
257n/a if not next.has_key(thiskw):
258n/a thiskw = ''
259n/a # end if
260n/a if thiskw in ('def', 'class'):
261n/a thisid = m.group('id')
262n/a else:
263n/a thisid = ''
264n/a # end if
265n/a elif line[i:i+1] in ('\n', '#'):
266n/a todo.append(line)
267n/a continue
268n/a else:
269n/a thiskw = ''
270n/a # end if
271n/a # end if
272n/a indent = len(line[:i].expandtabs(self.tabsize))
273n/a while indent < current:
274n/a if firstkw:
275n/a if topid:
276n/a s = '# end %s %s\n' % (
277n/a firstkw, topid)
278n/a else:
279n/a s = '# end %s\n' % firstkw
280n/a # end if
281n/a self.putline(s, current)
282n/a firstkw = lastkw = ''
283n/a # end if
284n/a current, firstkw, lastkw, topid = stack[-1]
285n/a del stack[-1]
286n/a # end while
287n/a if indent == current and firstkw:
288n/a if thiskw == 'end':
289n/a if endkw != firstkw:
290n/a self.error('mismatched end')
291n/a # end if
292n/a firstkw = lastkw = ''
293n/a elif not thiskw or thiskw in start:
294n/a if topid:
295n/a s = '# end %s %s\n' % (
296n/a firstkw, topid)
297n/a else:
298n/a s = '# end %s\n' % firstkw
299n/a # end if
300n/a self.putline(s, current)
301n/a firstkw = lastkw = topid = ''
302n/a # end if
303n/a # end if
304n/a if indent > current:
305n/a stack.append((current, firstkw, lastkw, topid))
306n/a if thiskw and thiskw not in start:
307n/a # error
308n/a thiskw = ''
309n/a # end if
310n/a current, firstkw, lastkw, topid = \
311n/a indent, thiskw, thiskw, thisid
312n/a # end if
313n/a if thiskw:
314n/a if thiskw in start:
315n/a firstkw = lastkw = thiskw
316n/a topid = thisid
317n/a else:
318n/a lastkw = thiskw
319n/a # end if
320n/a # end if
321n/a for l in todo: self.write(l)
322n/a # end for
323n/a todo = []
324n/a if not line: break
325n/a # end if
326n/a self.write(line)
327n/a # end while
328n/a # end def complete
329n/a
330n/a# end class PythonIndenter
331n/a
332n/a# Simplified user interface
333n/a# - xxx_filter(input, output): read and write file objects
334n/a# - xxx_string(s): take and return string object
335n/a# - xxx_file(filename): process file in place, return true iff changed
336n/a
337n/adef complete_filter(input = sys.stdin, output = sys.stdout,
338n/a stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
339n/a pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
340n/a pi.complete()
341n/a# end def complete_filter
342n/a
343n/adef delete_filter(input= sys.stdin, output = sys.stdout,
344n/a stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
345n/a pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
346n/a pi.delete()
347n/a# end def delete_filter
348n/a
349n/adef reformat_filter(input = sys.stdin, output = sys.stdout,
350n/a stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
351n/a pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
352n/a pi.reformat()
353n/a# end def reformat_filter
354n/a
355n/aclass StringReader:
356n/a def __init__(self, buf):
357n/a self.buf = buf
358n/a self.pos = 0
359n/a self.len = len(self.buf)
360n/a # end def __init__
361n/a def read(self, n = 0):
362n/a if n <= 0:
363n/a n = self.len - self.pos
364n/a else:
365n/a n = min(n, self.len - self.pos)
366n/a # end if
367n/a r = self.buf[self.pos : self.pos + n]
368n/a self.pos = self.pos + n
369n/a return r
370n/a # end def read
371n/a def readline(self):
372n/a i = self.buf.find('\n', self.pos)
373n/a return self.read(i + 1 - self.pos)
374n/a # end def readline
375n/a def readlines(self):
376n/a lines = []
377n/a line = self.readline()
378n/a while line:
379n/a lines.append(line)
380n/a line = self.readline()
381n/a # end while
382n/a return lines
383n/a # end def readlines
384n/a # seek/tell etc. are left as an exercise for the reader
385n/a# end class StringReader
386n/a
387n/aclass StringWriter:
388n/a def __init__(self):
389n/a self.buf = ''
390n/a # end def __init__
391n/a def write(self, s):
392n/a self.buf = self.buf + s
393n/a # end def write
394n/a def getvalue(self):
395n/a return self.buf
396n/a # end def getvalue
397n/a# end class StringWriter
398n/a
399n/adef complete_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
400n/a input = StringReader(source)
401n/a output = StringWriter()
402n/a pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
403n/a pi.complete()
404n/a return output.getvalue()
405n/a# end def complete_string
406n/a
407n/adef delete_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
408n/a input = StringReader(source)
409n/a output = StringWriter()
410n/a pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
411n/a pi.delete()
412n/a return output.getvalue()
413n/a# end def delete_string
414n/a
415n/adef reformat_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
416n/a input = StringReader(source)
417n/a output = StringWriter()
418n/a pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
419n/a pi.reformat()
420n/a return output.getvalue()
421n/a# end def reformat_string
422n/a
423n/adef complete_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
424n/a source = open(filename, 'r').read()
425n/a result = complete_string(source, stepsize, tabsize, expandtabs)
426n/a if source == result: return 0
427n/a # end if
428n/a import os
429n/a try: os.rename(filename, filename + '~')
430n/a except os.error: pass
431n/a # end try
432n/a f = open(filename, 'w')
433n/a f.write(result)
434n/a f.close()
435n/a return 1
436n/a# end def complete_file
437n/a
438n/adef delete_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
439n/a source = open(filename, 'r').read()
440n/a result = delete_string(source, stepsize, tabsize, expandtabs)
441n/a if source == result: return 0
442n/a # end if
443n/a import os
444n/a try: os.rename(filename, filename + '~')
445n/a except os.error: pass
446n/a # end try
447n/a f = open(filename, 'w')
448n/a f.write(result)
449n/a f.close()
450n/a return 1
451n/a# end def delete_file
452n/a
453n/adef reformat_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
454n/a source = open(filename, 'r').read()
455n/a result = reformat_string(source, stepsize, tabsize, expandtabs)
456n/a if source == result: return 0
457n/a # end if
458n/a import os
459n/a try: os.rename(filename, filename + '~')
460n/a except os.error: pass
461n/a # end try
462n/a f = open(filename, 'w')
463n/a f.write(result)
464n/a f.close()
465n/a return 1
466n/a# end def reformat_file
467n/a
468n/a# Test program when called as a script
469n/a
470n/ausage = """
471n/ausage: pindent (-c|-d|-r) [-s stepsize] [-t tabsize] [-e] [file] ...
472n/a-c : complete a correctly indented program (add #end directives)
473n/a-d : delete #end directives
474n/a-r : reformat a completed program (use #end directives)
475n/a-s stepsize: indentation step (default %(STEPSIZE)d)
476n/a-t tabsize : the worth in spaces of a tab (default %(TABSIZE)d)
477n/a-e : expand TABs into spaces (defailt OFF)
478n/a[file] ... : files are changed in place, with backups in file~
479n/aIf no files are specified or a single - is given,
480n/athe program acts as a filter (reads stdin, writes stdout).
481n/a""" % vars()
482n/a
483n/adef error_both(op1, op2):
484n/a sys.stderr.write('Error: You can not specify both '+op1+' and -'+op2[0]+' at the same time\n')
485n/a sys.stderr.write(usage)
486n/a sys.exit(2)
487n/a# end def error_both
488n/a
489n/adef test():
490n/a import getopt
491n/a try:
492n/a opts, args = getopt.getopt(sys.argv[1:], 'cdrs:t:e')
493n/a except getopt.error, msg:
494n/a sys.stderr.write('Error: %s\n' % msg)
495n/a sys.stderr.write(usage)
496n/a sys.exit(2)
497n/a # end try
498n/a action = None
499n/a stepsize = STEPSIZE
500n/a tabsize = TABSIZE
501n/a expandtabs = EXPANDTABS
502n/a for o, a in opts:
503n/a if o == '-c':
504n/a if action: error_both(o, action)
505n/a # end if
506n/a action = 'complete'
507n/a elif o == '-d':
508n/a if action: error_both(o, action)
509n/a # end if
510n/a action = 'delete'
511n/a elif o == '-r':
512n/a if action: error_both(o, action)
513n/a # end if
514n/a action = 'reformat'
515n/a elif o == '-s':
516n/a stepsize = int(a)
517n/a elif o == '-t':
518n/a tabsize = int(a)
519n/a elif o == '-e':
520n/a expandtabs = 1
521n/a # end if
522n/a # end for
523n/a if not action:
524n/a sys.stderr.write(
525n/a 'You must specify -c(omplete), -d(elete) or -r(eformat)\n')
526n/a sys.stderr.write(usage)
527n/a sys.exit(2)
528n/a # end if
529n/a if not args or args == ['-']:
530n/a action = eval(action + '_filter')
531n/a action(sys.stdin, sys.stdout, stepsize, tabsize, expandtabs)
532n/a else:
533n/a action = eval(action + '_file')
534n/a for filename in args:
535n/a action(filename, stepsize, tabsize, expandtabs)
536n/a # end for
537n/a # end if
538n/a# end def test
539n/a
540n/aif __name__ == '__main__':
541n/a test()
542n/a# end if