blob: 5eaf50ea65d6462a24bb039e07e25cc71af96aa9 [file] [log] [blame]
Guido van Rossumce858271998-09-14 15:43:38 +00001#! /usr/bin/env python
2
3"Replace tabs with spaces in argument files. Print names of changed files."
4
5import os
6import sys
Guido van Rossumce858271998-09-14 15:43:38 +00007import getopt
8
9def main():
10 tabsize = 8
11 try:
12 opts, args = getopt.getopt(sys.argv[1:], "t:")
13 if not args:
14 raise getopt.error, "At least one file argument required"
15 except getopt.error, msg:
16 print msg
Guido van Rossum8fd0f141998-10-20 15:33:33 +000017 print "usage:", sys.argv[0], "[-t tabwidth] file ..."
Guido van Rossumce858271998-09-14 15:43:38 +000018 return
Guido van Rossum8fd0f141998-10-20 15:33:33 +000019 for optname, optvalue in opts:
20 if optname == '-t':
21 tabsize = int(optvalue)
Guido van Rossumce858271998-09-14 15:43:38 +000022
23 for file in args:
24 process(file, tabsize)
25
26def process(file, tabsize):
27 try:
28 f = open(file)
29 text = f.read()
30 f.close()
31 except IOError, msg:
32 print "%s: I/O error: %s" % (`file`, str(msg))
33 return
Walter Dörwaldaaab30e2002-09-11 20:36:02 +000034 newtext = text.expandtabs(tabsize)
Guido van Rossumce858271998-09-14 15:43:38 +000035 if newtext == text:
36 return
37 backup = file + "~"
38 try:
39 os.unlink(backup)
40 except os.error:
41 pass
42 try:
43 os.rename(file, backup)
44 except os.error:
45 pass
46 f = open(file, "w")
47 f.write(newtext)
48 f.close()
49 print file
50
51if __name__ == '__main__':
52 main()