44
55"""reindent [-d][-r][-v] [ path ... ]
66
7- -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- -v (--verbose) Verbose. Print informative msgs; else no output.
10- -h (--help) Help. Print this usage information and exit.
7+ -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.
11+ -h (--help) Help. Print this usage information and exit.
1112
1213Change Python (.py) files to use 4-space indents and no hard tab characters.
1314Also trim excess spaces and tabs from ends of lines, and remove empty lines
3132The hard part of reindenting is figuring out what to do with comment
3233lines. So long as the input files get a clean bill of health from
3334tabnanny.py, reindent should do a good job.
35+
36+ The backup file is a copy of the one that is being reindented. The ".bak"
37+ file is generated with shutil.copy(), but some corner cases regarding
38+ user/group and permissions could leave the backup file more readable that
39+ you'd prefer. You can always use the --nobackup option to prevent this.
3440"""
3541
3642__version__ = "1"
3743
3844import tokenize
39- import os
45+ import os , shutil
4046import sys
4147
42- verbose = 0
43- recurse = 0
44- dryrun = 0
48+ verbose = 0
49+ recurse = 0
50+ dryrun = 0
51+ makebackup = True
4552
4653def usage (msg = None ):
4754 if msg is not None :
@@ -57,10 +64,10 @@ def errprint(*args):
5764
5865def main ():
5966 import getopt
60- global verbose , recurse , dryrun
67+ global verbose , recurse , dryrun , makebackup
6168 try :
62- opts , args = getopt .getopt (sys .argv [1 :], "drvh " ,
63- ["dryrun" , "recurse" , "verbose" , "help" ])
69+ opts , args = getopt .getopt (sys .argv [1 :], "drnvh " ,
70+ ["dryrun" , "recurse" , "nobackup " , "verbose" , "help" ])
6471 except getopt .error , msg :
6572 usage (msg )
6673 return
@@ -69,6 +76,8 @@ def main():
6976 dryrun += 1
7077 elif o in ('-r' , '--recurse' ):
7178 recurse += 1
79+ elif o in ('-n' , '--nobackup' ):
80+ makebackup = False
7281 elif o in ('-v' , '--verbose' ):
7382 verbose += 1
7483 elif o in ('-h' , '--help' ):
@@ -112,11 +121,10 @@ def check(file):
112121 print "But this is a dry run, so leaving it alone."
113122 if not dryrun :
114123 bak = file + ".bak"
115- if os .path .exists (bak ):
116- os .remove (bak )
117- os .rename (file , bak )
118- if verbose :
119- print "renamed" , file , "to" , bak
124+ if makebackup :
125+ shutil .copyfile (file , bak )
126+ if verbose :
127+ print "backed up" , file , "to" , bak
120128 f = open (file , "w" )
121129 r .write (f )
122130 f .close ()
0 commit comments