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