PageRenderTime 52ms CodeModel.GetById 30ms app.highlight 4ms RepoModel.GetById 16ms app.codeStats 0ms

/Tools/scripts/untabify.py

http://unladen-swallow.googlecode.com/
Python | 52 lines | 45 code | 6 blank | 1 comment | 9 complexity | 536f9da7d7fb265a0b8fd0e5555c8748 MD5 | raw file
 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):
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    f = open(filename, "w")
47    f.write(newtext)
48    f.close()
49    print filename
50
51if __name__ == '__main__':
52    main()