blob: 18424dea1437acab186112a36ab31d47d79208a2 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Tim Petersad147202000-10-05 03:48:38 +00002
3# Released to the public domain, by Tim Peters, 03 October 2000.
4
Skip Montanaro9a29e7a2002-03-26 11:39:26 +00005"""reindent [-d][-r][-v] [ path ... ]
Tim Petersad147202000-10-05 03:48:38 +00006
Christian Heimes7131fd92008-02-19 14:21:46 +00007-d (--dryrun) Dry run. Analyze, but don't make any changes to, files.
8-r (--recurse) Recurse. Search for all .py files in subdirectories too.
9-n (--nobackup) No backup. Does not make a ".bak" file before reindenting.
10-v (--verbose) Verbose. Print informative msgs; else no output.
Jason R. Coombs76eec3d2011-07-26 11:38:04 -040011 (--newline) Newline. Specify the newline character to use (CRLF, LF).
12 Default is the same as the original file.
Christian Heimes7131fd92008-02-19 14:21:46 +000013-h (--help) Help. Print this usage information and exit.
Tim Petersad147202000-10-05 03:48:38 +000014
15Change Python (.py) files to use 4-space indents and no hard tab characters.
Tim Petersba001a02001-10-04 19:44:10 +000016Also trim excess spaces and tabs from ends of lines, and remove empty lines
17at the end of files. Also ensure the last line ends with a newline.
Tim Petersad147202000-10-05 03:48:38 +000018
Skip Montanaro9a29e7a2002-03-26 11:39:26 +000019If no paths are given on the command line, reindent operates as a filter,
20reading a single source file from standard input and writing the transformed
21source to standard output. In this case, the -d, -r and -v flags are
22ignored.
Tim Petersad147202000-10-05 03:48:38 +000023
Skip Montanaro9a29e7a2002-03-26 11:39:26 +000024You can pass one or more file and/or directory paths. When a directory
25path, all .py files within the directory will be examined, and, if the -r
26option is given, likewise recursively for subdirectories.
27
28If output is not to standard output, reindent overwrites files in place,
29renaming the originals with a .bak extension. If it finds nothing to
30change, the file is left alone. If reindent does change a file, the changed
31file is a fixed-point for future runs (i.e., running reindent on the
32resulting .py file won't change it again).
Tim Petersad147202000-10-05 03:48:38 +000033
34The hard part of reindenting is figuring out what to do with comment
35lines. So long as the input files get a clean bill of health from
36tabnanny.py, reindent should do a good job.
Christian Heimes7131fd92008-02-19 14:21:46 +000037
38The backup file is a copy of the one that is being reindented. The ".bak"
39file is generated with shutil.copy(), but some corner cases regarding
Jason R. Coombs76748b72011-07-26 11:18:40 -040040user/group and permissions could leave the backup file more readable than
Christian Heimes7131fd92008-02-19 14:21:46 +000041you'd prefer. You can always use the --nobackup option to prevent this.
Tim Petersad147202000-10-05 03:48:38 +000042"""
43
44__version__ = "1"
45
46import tokenize
Florent Xiclunae4a33802010-08-09 12:24:20 +000047import os
48import shutil
Tim Petersad147202000-10-05 03:48:38 +000049import sys
50
Florent Xiclunae4a33802010-08-09 12:24:20 +000051verbose = False
52recurse = False
53dryrun = False
Christian Heimes7131fd92008-02-19 14:21:46 +000054makebackup = True
Victor Stinner765531d2013-03-26 01:11:54 +010055# A specified newline to be used in the output (set by --newline option)
Jason R. Coombs47891042011-07-29 09:31:56 -040056spec_newline = None
Tim Petersad147202000-10-05 03:48:38 +000057
Florent Xiclunae4a33802010-08-09 12:24:20 +000058
Skip Montanaro165163f2004-03-27 18:43:56 +000059def usage(msg=None):
Florent Xiclunae4a33802010-08-09 12:24:20 +000060 if msg is None:
61 msg = __doc__
62 print(msg, file=sys.stderr)
63
Skip Montanaro165163f2004-03-27 18:43:56 +000064
Tim Petersad147202000-10-05 03:48:38 +000065def errprint(*args):
Florent Xiclunae4a33802010-08-09 12:24:20 +000066 sys.stderr.write(" ".join(str(arg) for arg in args))
Tim Petersad147202000-10-05 03:48:38 +000067 sys.stderr.write("\n")
68
69def main():
70 import getopt
Jason R. Coombs76eec3d2011-07-26 11:38:04 -040071 global verbose, recurse, dryrun, makebackup, spec_newline
Tim Petersad147202000-10-05 03:48:38 +000072 try:
Christian Heimes7131fd92008-02-19 14:21:46 +000073 opts, args = getopt.getopt(sys.argv[1:], "drnvh",
Jason R. Coombs76eec3d2011-07-26 11:38:04 -040074 ["dryrun", "recurse", "nobackup", "verbose", "newline=", "help"])
Guido van Rossumb940e112007-01-10 16:19:56 +000075 except getopt.error as msg:
Skip Montanaro165163f2004-03-27 18:43:56 +000076 usage(msg)
Tim Petersad147202000-10-05 03:48:38 +000077 return
78 for o, a in opts:
Skip Montanaro165163f2004-03-27 18:43:56 +000079 if o in ('-d', '--dryrun'):
Florent Xiclunae4a33802010-08-09 12:24:20 +000080 dryrun = True
Skip Montanaro165163f2004-03-27 18:43:56 +000081 elif o in ('-r', '--recurse'):
Florent Xiclunae4a33802010-08-09 12:24:20 +000082 recurse = True
Christian Heimes7131fd92008-02-19 14:21:46 +000083 elif o in ('-n', '--nobackup'):
84 makebackup = False
Skip Montanaro165163f2004-03-27 18:43:56 +000085 elif o in ('-v', '--verbose'):
Florent Xiclunae4a33802010-08-09 12:24:20 +000086 verbose = True
Jason R. Coombs76eec3d2011-07-26 11:38:04 -040087 elif o in ('--newline',):
88 if not a.upper() in ('CRLF', 'LF'):
89 usage()
90 return
91 spec_newline = dict(CRLF='\r\n', LF='\n')[a.upper()]
Skip Montanaro165163f2004-03-27 18:43:56 +000092 elif o in ('-h', '--help'):
93 usage()
94 return
Tim Petersad147202000-10-05 03:48:38 +000095 if not args:
Skip Montanaro9a29e7a2002-03-26 11:39:26 +000096 r = Reindenter(sys.stdin)
97 r.run()
98 r.write(sys.stdout)
Tim Petersad147202000-10-05 03:48:38 +000099 return
100 for arg in args:
101 check(arg)
102
Florent Xiclunae4a33802010-08-09 12:24:20 +0000103
Tim Petersad147202000-10-05 03:48:38 +0000104def check(file):
105 if os.path.isdir(file) and not os.path.islink(file):
106 if verbose:
Guido van Rossum6247fdb2007-04-27 19:48:23 +0000107 print("listing directory", file)
Tim Petersad147202000-10-05 03:48:38 +0000108 names = os.listdir(file)
109 for name in names:
110 fullname = os.path.join(file, name)
111 if ((recurse and os.path.isdir(fullname) and
Benjamin Peterson206e3072008-10-19 14:07:49 +0000112 not os.path.islink(fullname) and
113 not os.path.split(fullname)[1].startswith("."))
Tim Petersad147202000-10-05 03:48:38 +0000114 or name.lower().endswith(".py")):
115 check(fullname)
116 return
117
118 if verbose:
Guido van Rossum6247fdb2007-04-27 19:48:23 +0000119 print("checking", file, "...", end=' ')
Jason R. Coombs76748b72011-07-26 11:18:40 -0400120 with open(file, 'rb') as f:
Alexander Belopolsky4a98e3b2010-10-18 14:43:38 +0000121 encoding, _ = tokenize.detect_encoding(f.readline)
Tim Petersad147202000-10-05 03:48:38 +0000122 try:
Alexander Belopolsky4a98e3b2010-10-18 14:43:38 +0000123 with open(file, encoding=encoding) as f:
Florent Xiclunae4a33802010-08-09 12:24:20 +0000124 r = Reindenter(f)
Guido van Rossumb940e112007-01-10 16:19:56 +0000125 except IOError as msg:
Tim Petersad147202000-10-05 03:48:38 +0000126 errprint("%s: I/O Error: %s" % (file, str(msg)))
127 return
128
Jason R. Coombs76eec3d2011-07-26 11:38:04 -0400129 newline = spec_newline if spec_newline else r.newlines
Jason R. Coombs76748b72011-07-26 11:18:40 -0400130 if isinstance(newline, tuple):
Jason R. Coombs76eec3d2011-07-26 11:38:04 -0400131 errprint("%s: mixed newlines detected; cannot continue without --newline" % file)
Jason R. Coombs76748b72011-07-26 11:18:40 -0400132 return
133
Tim Petersad147202000-10-05 03:48:38 +0000134 if r.run():
135 if verbose:
Guido van Rossum6247fdb2007-04-27 19:48:23 +0000136 print("changed.")
Tim Petersad147202000-10-05 03:48:38 +0000137 if dryrun:
Guido van Rossum6247fdb2007-04-27 19:48:23 +0000138 print("But this is a dry run, so leaving it alone.")
Tim Petersad147202000-10-05 03:48:38 +0000139 if not dryrun:
140 bak = file + ".bak"
Christian Heimes7131fd92008-02-19 14:21:46 +0000141 if makebackup:
142 shutil.copyfile(file, bak)
143 if verbose:
144 print("backed up", file, "to", bak)
Jason R. Coombs76748b72011-07-26 11:18:40 -0400145 with open(file, "w", encoding=encoding, newline=newline) as f:
Florent Xiclunae4a33802010-08-09 12:24:20 +0000146 r.write(f)
Tim Petersad147202000-10-05 03:48:38 +0000147 if verbose:
Guido van Rossum6247fdb2007-04-27 19:48:23 +0000148 print("wrote new", file)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000149 return True
Tim Petersad147202000-10-05 03:48:38 +0000150 else:
151 if verbose:
Guido van Rossum6247fdb2007-04-27 19:48:23 +0000152 print("unchanged.")
Christian Heimesada8c3b2008-03-18 18:26:33 +0000153 return False
Tim Petersad147202000-10-05 03:48:38 +0000154
Florent Xiclunae4a33802010-08-09 12:24:20 +0000155
Tim Petersba001a02001-10-04 19:44:10 +0000156def _rstrip(line, JUNK='\n \t'):
157 """Return line stripped of trailing spaces, tabs, newlines.
158
159 Note that line.rstrip() instead also strips sundry control characters,
160 but at least one known Emacs user expects to keep junk like that, not
161 mentioning Barry by name or anything <wink>.
162 """
163
164 i = len(line)
Florent Xiclunae4a33802010-08-09 12:24:20 +0000165 while i > 0 and line[i - 1] in JUNK:
Tim Petersba001a02001-10-04 19:44:10 +0000166 i -= 1
167 return line[:i]
168
Florent Xiclunae4a33802010-08-09 12:24:20 +0000169
Tim Petersad147202000-10-05 03:48:38 +0000170class Reindenter:
171
172 def __init__(self, f):
173 self.find_stmt = 1 # next token begins a fresh stmt?
174 self.level = 0 # current indent level
175
176 # Raw file lines.
177 self.raw = f.readlines()
178
179 # File lines, rstripped & tab-expanded. Dummy at start is so
180 # that we can use tokenize's 1-based line numbering easily.
181 # Note that a line is all-blank iff it's "\n".
Tim Petersba001a02001-10-04 19:44:10 +0000182 self.lines = [_rstrip(line).expandtabs() + "\n"
Tim Petersad147202000-10-05 03:48:38 +0000183 for line in self.raw]
184 self.lines.insert(0, None)
185 self.index = 1 # index into self.lines of next line
186
187 # List of (lineno, indentlevel) pairs, one for each stmt and
188 # comment line. indentlevel is -1 for comment lines, as a
189 # signal that tokenize doesn't know what to do about them;
190 # indeed, they're our headache!
191 self.stats = []
192
Jason R. Coombs76748b72011-07-26 11:18:40 -0400193 # Save the newlines found in the file so they can be used to
194 # create output without mutating the newlines.
195 self.newlines = f.newlines
196
Tim Petersad147202000-10-05 03:48:38 +0000197 def run(self):
Trent Nelson428de652008-03-18 22:41:35 +0000198 tokens = tokenize.generate_tokens(self.getline)
199 for _token in tokens:
200 self.tokeneater(*_token)
Tim Petersad147202000-10-05 03:48:38 +0000201 # Remove trailing empty lines.
202 lines = self.lines
203 while lines and lines[-1] == "\n":
204 lines.pop()
205 # Sentinel.
206 stats = self.stats
207 stats.append((len(lines), 0))
208 # Map count of leading spaces to # we want.
209 have2want = {}
210 # Program after transformation.
211 after = self.after = []
Tim Peters54e5b892002-02-17 07:03:05 +0000212 # Copy over initial empty lines -- there's nothing to do until
213 # we see a line with *something* on it.
214 i = stats[0][0]
215 after.extend(lines[1:i])
Florent Xiclunae4a33802010-08-09 12:24:20 +0000216 for i in range(len(stats) - 1):
Tim Petersad147202000-10-05 03:48:38 +0000217 thisstmt, thislevel = stats[i]
Florent Xiclunae4a33802010-08-09 12:24:20 +0000218 nextstmt = stats[i + 1][0]
Tim Petersad147202000-10-05 03:48:38 +0000219 have = getlspace(lines[thisstmt])
220 want = thislevel * 4
221 if want < 0:
222 # A comment line.
223 if have:
224 # An indented comment line. If we saw the same
225 # indentation before, reuse what it most recently
226 # mapped to.
227 want = have2want.get(have, -1)
228 if want < 0:
229 # Then it probably belongs to the next real stmt.
Florent Xiclunae4a33802010-08-09 12:24:20 +0000230 for j in range(i + 1, len(stats) - 1):
Tim Petersad147202000-10-05 03:48:38 +0000231 jline, jlevel = stats[j]
232 if jlevel >= 0:
233 if have == getlspace(lines[jline]):
234 want = jlevel * 4
235 break
236 if want < 0: # Maybe it's a hanging
237 # comment like this one,
238 # in which case we should shift it like its base
239 # line got shifted.
Florent Xiclunae4a33802010-08-09 12:24:20 +0000240 for j in range(i - 1, -1, -1):
Tim Petersad147202000-10-05 03:48:38 +0000241 jline, jlevel = stats[j]
242 if jlevel >= 0:
Florent Xiclunae4a33802010-08-09 12:24:20 +0000243 want = have + (getlspace(after[jline - 1]) -
244 getlspace(lines[jline]))
Tim Petersad147202000-10-05 03:48:38 +0000245 break
246 if want < 0:
247 # Still no luck -- leave it alone.
248 want = have
249 else:
250 want = 0
251 assert want >= 0
252 have2want[have] = want
253 diff = want - have
254 if diff == 0 or have == 0:
255 after.extend(lines[thisstmt:nextstmt])
256 else:
257 for line in lines[thisstmt:nextstmt]:
258 if diff > 0:
259 if line == "\n":
260 after.append(line)
261 else:
262 after.append(" " * diff + line)
263 else:
264 remove = min(getlspace(line), -diff)
265 after.append(line[remove:])
266 return self.raw != self.after
267
268 def write(self, f):
269 f.writelines(self.after)
270
271 # Line-getter for tokenize.
272 def getline(self):
273 if self.index >= len(self.lines):
274 line = ""
275 else:
276 line = self.lines[self.index]
277 self.index += 1
278 return line
279
280 # Line-eater for tokenize.
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000281 def tokeneater(self, type, token, slinecol, end, line,
Tim Petersad147202000-10-05 03:48:38 +0000282 INDENT=tokenize.INDENT,
283 DEDENT=tokenize.DEDENT,
284 NEWLINE=tokenize.NEWLINE,
285 COMMENT=tokenize.COMMENT,
286 NL=tokenize.NL):
287
288 if type == NEWLINE:
289 # A program statement, or ENDMARKER, will eventually follow,
290 # after some (possibly empty) run of tokens of the form
291 # (NL | COMMENT)* (INDENT | DEDENT+)?
292 self.find_stmt = 1
293
294 elif type == INDENT:
295 self.find_stmt = 1
296 self.level += 1
297
298 elif type == DEDENT:
299 self.find_stmt = 1
300 self.level -= 1
301
302 elif type == COMMENT:
303 if self.find_stmt:
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000304 self.stats.append((slinecol[0], -1))
Tim Petersad147202000-10-05 03:48:38 +0000305 # but we're still looking for a new stmt, so leave
306 # find_stmt alone
307
308 elif type == NL:
309 pass
310
311 elif self.find_stmt:
312 # This is the first "real token" following a NEWLINE, so it
313 # must be the first token of the next program statement, or an
314 # ENDMARKER.
315 self.find_stmt = 0
316 if line: # not endmarker
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000317 self.stats.append((slinecol[0], self.level))
Tim Petersad147202000-10-05 03:48:38 +0000318
Florent Xiclunae4a33802010-08-09 12:24:20 +0000319
Tim Petersad147202000-10-05 03:48:38 +0000320# Count number of leading blanks.
321def getlspace(line):
322 i, n = 0, len(line)
323 while i < n and line[i] == " ":
324 i += 1
325 return i
326
Florent Xiclunae4a33802010-08-09 12:24:20 +0000327
Tim Petersad147202000-10-05 03:48:38 +0000328if __name__ == '__main__':
329 main()