reindent.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #! /usr/bin/env python
  2. # FROM http://svn.python.org/view/python/trunk/Tools/scripts/reindent.py
  3. #
  4. # Released to the public domain, by Tim Peters, 03 October 2000.
  5. """reindent [-d][-r][-v] [ path ... ]
  6. -d (--dryrun) Dry run. Analyze, but don't make any changes to, files.
  7. -r (--recurse) Recurse. Search for all .py files in subdirectories too.
  8. -n (--nobackup) No backup. Does not make a ".bak" file before reindenting.
  9. -v (--verbose) Verbose. Print informative msgs; else no output.
  10. -h (--help) Help. Print this usage information and exit.
  11. Change Python (.py) files to use 4-space indents and no hard tab characters.
  12. Also trim excess spaces and tabs from ends of lines, and remove empty lines
  13. at the end of files. Also ensure the last line ends with a newline.
  14. If no paths are given on the command line, reindent operates as a filter,
  15. reading a single source file from standard input and writing the transformed
  16. source to standard output. In this case, the -d, -r and -v flags are
  17. ignored.
  18. You can pass one or more file and/or directory paths. When a directory
  19. path, all .py files within the directory will be examined, and, if the -r
  20. option is given, likewise recursively for subdirectories.
  21. If output is not to standard output, reindent overwrites files in place,
  22. renaming the originals with a .bak extension. If it finds nothing to
  23. change, the file is left alone. If reindent does change a file, the changed
  24. file is a fixed-point for future runs (i.e., running reindent on the
  25. resulting .py file won't change it again).
  26. The hard part of reindenting is figuring out what to do with comment
  27. lines. So long as the input files get a clean bill of health from
  28. tabnanny.py, reindent should do a good job.
  29. The backup file is a copy of the one that is being reindented. The ".bak"
  30. file is generated with shutil.copy(), but some corner cases regarding
  31. user/group and permissions could leave the backup file more readable that
  32. you'd prefer. You can always use the --nobackup option to prevent this.
  33. """
  34. __version__ = "1"
  35. import tokenize
  36. import os, shutil
  37. import sys
  38. verbose = 0
  39. recurse = 0
  40. dryrun = 0
  41. makebackup = True
  42. def usage(msg=None):
  43. if msg is not None:
  44. print >> sys.stderr, msg
  45. print >> sys.stderr, __doc__
  46. def errprint(*args):
  47. sep = ""
  48. for arg in args:
  49. sys.stderr.write(sep + str(arg))
  50. sep = " "
  51. sys.stderr.write("\n")
  52. def main():
  53. import getopt
  54. global verbose, recurse, dryrun, makebackup
  55. try:
  56. opts, args = getopt.getopt(sys.argv[1:], "drnvh",
  57. ["dryrun", "recurse", "nobackup", "verbose", "help"])
  58. except getopt.error, msg:
  59. usage(msg)
  60. return
  61. for o, a in opts:
  62. if o in ('-d', '--dryrun'):
  63. dryrun += 1
  64. elif o in ('-r', '--recurse'):
  65. recurse += 1
  66. elif o in ('-n', '--nobackup'):
  67. makebackup = False
  68. elif o in ('-v', '--verbose'):
  69. verbose += 1
  70. elif o in ('-h', '--help'):
  71. usage()
  72. return
  73. if not args:
  74. r = Reindenter(sys.stdin)
  75. r.run()
  76. r.write(sys.stdout)
  77. return
  78. for arg in args:
  79. check(arg)
  80. def check(file):
  81. if os.path.isdir(file) and not os.path.islink(file):
  82. if verbose:
  83. print "listing directory", file
  84. names = os.listdir(file)
  85. for name in names:
  86. fullname = os.path.join(file, name)
  87. if ((recurse and os.path.isdir(fullname) and
  88. not os.path.islink(fullname) and
  89. not os.path.split(fullname)[1].startswith("."))
  90. or name.lower().endswith(".py")):
  91. check(fullname)
  92. return
  93. if verbose:
  94. print "checking", file, "...",
  95. try:
  96. f = open(file)
  97. except IOError, msg:
  98. errprint("%s: I/O Error: %s" % (file, str(msg)))
  99. return
  100. r = Reindenter(f)
  101. f.close()
  102. if r.run():
  103. if verbose:
  104. print "changed."
  105. if dryrun:
  106. print "But this is a dry run, so leaving it alone."
  107. if not dryrun:
  108. bak = file + ".bak"
  109. if makebackup:
  110. shutil.copyfile(file, bak)
  111. if verbose:
  112. print "backed up", file, "to", bak
  113. f = open(file, "w")
  114. r.write(f)
  115. f.close()
  116. if verbose:
  117. print "wrote new", file
  118. return True
  119. else:
  120. if verbose:
  121. print "unchanged."
  122. return False
  123. def _rstrip(line, JUNK='\n \t'):
  124. """Return line stripped of trailing spaces, tabs, newlines.
  125. Note that line.rstrip() instead also strips sundry control characters,
  126. but at least one known Emacs user expects to keep junk like that, not
  127. mentioning Barry by name or anything <wink>.
  128. """
  129. i = len(line)
  130. while i > 0 and line[i-1] in JUNK:
  131. i -= 1
  132. return line[:i]
  133. class Reindenter:
  134. def __init__(self, f):
  135. self.find_stmt = 1 # next token begins a fresh stmt?
  136. self.level = 0 # current indent level
  137. # Raw file lines.
  138. self.raw = f.readlines()
  139. # File lines, rstripped & tab-expanded. Dummy at start is so
  140. # that we can use tokenize's 1-based line numbering easily.
  141. # Note that a line is all-blank iff it's "\n".
  142. self.lines = [_rstrip(line).expandtabs() + "\n"
  143. for line in self.raw]
  144. self.lines.insert(0, None)
  145. self.index = 1 # index into self.lines of next line
  146. # List of (lineno, indentlevel) pairs, one for each stmt and
  147. # comment line. indentlevel is -1 for comment lines, as a
  148. # signal that tokenize doesn't know what to do about them;
  149. # indeed, they're our headache!
  150. self.stats = []
  151. def run(self):
  152. tokenize.tokenize(self.getline, self.tokeneater)
  153. # Remove trailing empty lines.
  154. lines = self.lines
  155. while lines and lines[-1] == "\n":
  156. lines.pop()
  157. # Sentinel.
  158. stats = self.stats
  159. stats.append((len(lines), 0))
  160. # Map count of leading spaces to # we want.
  161. have2want = {}
  162. # Program after transformation.
  163. after = self.after = []
  164. # Copy over initial empty lines -- there's nothing to do until
  165. # we see a line with *something* on it.
  166. i = stats[0][0]
  167. after.extend(lines[1:i])
  168. for i in range(len(stats)-1):
  169. thisstmt, thislevel = stats[i]
  170. nextstmt = stats[i+1][0]
  171. have = getlspace(lines[thisstmt])
  172. want = thislevel * 4
  173. if want < 0:
  174. # A comment line.
  175. if have:
  176. # An indented comment line. If we saw the same
  177. # indentation before, reuse what it most recently
  178. # mapped to.
  179. want = have2want.get(have, -1)
  180. if want < 0:
  181. # Then it probably belongs to the next real stmt.
  182. for j in xrange(i+1, len(stats)-1):
  183. jline, jlevel = stats[j]
  184. if jlevel >= 0:
  185. if have == getlspace(lines[jline]):
  186. want = jlevel * 4
  187. break
  188. if want < 0: # Maybe it's a hanging
  189. # comment like this one,
  190. # in which case we should shift it like its base
  191. # line got shifted.
  192. for j in xrange(i-1, -1, -1):
  193. jline, jlevel = stats[j]
  194. if jlevel >= 0:
  195. want = have + getlspace(after[jline-1]) - \
  196. getlspace(lines[jline])
  197. break
  198. if want < 0:
  199. # Still no luck -- leave it alone.
  200. want = have
  201. else:
  202. want = 0
  203. assert want >= 0
  204. have2want[have] = want
  205. diff = want - have
  206. if diff == 0 or have == 0:
  207. after.extend(lines[thisstmt:nextstmt])
  208. else:
  209. for line in lines[thisstmt:nextstmt]:
  210. if diff > 0:
  211. if line == "\n":
  212. after.append(line)
  213. else:
  214. after.append(" " * diff + line)
  215. else:
  216. remove = min(getlspace(line), -diff)
  217. after.append(line[remove:])
  218. return self.raw != self.after
  219. def write(self, f):
  220. f.writelines(self.after)
  221. # Line-getter for tokenize.
  222. def getline(self):
  223. if self.index >= len(self.lines):
  224. line = ""
  225. else:
  226. line = self.lines[self.index]
  227. self.index += 1
  228. return line
  229. # Line-eater for tokenize.
  230. def tokeneater(self, type, token, (sline, scol), end, line,
  231. INDENT=tokenize.INDENT,
  232. DEDENT=tokenize.DEDENT,
  233. NEWLINE=tokenize.NEWLINE,
  234. COMMENT=tokenize.COMMENT,
  235. NL=tokenize.NL):
  236. if type == NEWLINE:
  237. # A program statement, or ENDMARKER, will eventually follow,
  238. # after some (possibly empty) run of tokens of the form
  239. # (NL | COMMENT)* (INDENT | DEDENT+)?
  240. self.find_stmt = 1
  241. elif type == INDENT:
  242. self.find_stmt = 1
  243. self.level += 1
  244. elif type == DEDENT:
  245. self.find_stmt = 1
  246. self.level -= 1
  247. elif type == COMMENT:
  248. if self.find_stmt:
  249. self.stats.append((sline, -1))
  250. # but we're still looking for a new stmt, so leave
  251. # find_stmt alone
  252. elif type == NL:
  253. pass
  254. elif self.find_stmt:
  255. # This is the first "real token" following a NEWLINE, so it
  256. # must be the first token of the next program statement, or an
  257. # ENDMARKER.
  258. self.find_stmt = 0
  259. if line: # not endmarker
  260. self.stats.append((sline, self.level))
  261. # Count number of leading blanks.
  262. def getlspace(line):
  263. i, n = 0, len(line)
  264. while i < n and line[i] == " ":
  265. i += 1
  266. return i
  267. if __name__ == '__main__':
  268. main()