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