• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#! /usr/bin/env python
2
3"Replace tabs with spaces in argument files.  Print names of changed files."
4
5import os
6import sys
7import 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
17        print "usage:", sys.argv[0], "[-t tabwidth] file ..."
18        return
19    for optname, optvalue in opts:
20        if optname == '-t':
21            tabsize = int(optvalue)
22
23    for filename in args:
24        process(filename, tabsize)
25
26def process(filename, tabsize, verbose=True):
27    try:
28        f = open(filename)
29        text = f.read()
30        f.close()
31    except IOError, msg:
32        print "%r: I/O error: %s" % (filename, msg)
33        return
34    newtext = text.expandtabs(tabsize)
35    if newtext == text:
36        return
37    backup = filename + "~"
38    try:
39        os.unlink(backup)
40    except os.error:
41        pass
42    try:
43        os.rename(filename, backup)
44    except os.error:
45        pass
46    with open(filename, "w") as f:
47        f.write(newtext)
48    if verbose:
49        print filename
50
51if __name__ == '__main__':
52    main()
53