Guido van Rossum | ce85827 | 1998-09-14 15:43:38 +0000 | [diff] [blame] | 1 | #! /usr/bin/env python |
| 2 | |
| 3 | "Replace tabs with spaces in argument files. Print names of changed files." |
| 4 | |
| 5 | import os |
| 6 | import sys |
Guido van Rossum | ce85827 | 1998-09-14 15:43:38 +0000 | [diff] [blame] | 7 | import getopt |
| 8 | |
| 9 | def 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 Rossum | 8fd0f14 | 1998-10-20 15:33:33 +0000 | [diff] [blame] | 17 | print "usage:", sys.argv[0], "[-t tabwidth] file ..." |
Guido van Rossum | ce85827 | 1998-09-14 15:43:38 +0000 | [diff] [blame] | 18 | return |
Guido van Rossum | 8fd0f14 | 1998-10-20 15:33:33 +0000 | [diff] [blame] | 19 | for optname, optvalue in opts: |
| 20 | if optname == '-t': |
| 21 | tabsize = int(optvalue) |
Guido van Rossum | ce85827 | 1998-09-14 15:43:38 +0000 | [diff] [blame] | 22 | |
| 23 | for file in args: |
| 24 | process(file, tabsize) |
| 25 | |
| 26 | def 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örwald | aaab30e | 2002-09-11 20:36:02 +0000 | [diff] [blame] | 34 | newtext = text.expandtabs(tabsize) |
Guido van Rossum | ce85827 | 1998-09-14 15:43:38 +0000 | [diff] [blame] | 35 | 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 | |
| 51 | if __name__ == '__main__': |
| 52 | main() |