Skip to content

Instantly share code, notes, and snippets.

@michaelgruenewald
Created January 18, 2013 16:32
Show Gist options
  • Save michaelgruenewald/ef7911e5f7e2107d8ecd to your computer and use it in GitHub Desktop.
Save michaelgruenewald/ef7911e5f7e2107d8ecd to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import argparse
import ast
import re
import sys
TS = 4
def process_match(match):
col = 0
for c in match.group(0):
if c == " ":
col += 1
elif c == "\t":
col = col - col % TS + TS
elif c == "\n":
return "\n"
else:
raise ValueError("Unknown character %r" % c)
return " " * col
def process_line(line):
return re.sub(r"^\s*", process_match, line)
def process_file(filename):
with open(filename) as f:
lines = f.readlines()
old_ast = ast.parse("".join(lines), filename)
lines = map(process_line, lines)
new_ast = ast.parse("".join(lines), filename)
if ast.dump(old_ast) == ast.dump(new_ast):
with open(filename, "w") as f:
f.writelines(lines)
else:
print >> sys.stdout, "%s: Not writing changes because AST would change."
return False
return True
def main():
arg_parser = argparse.ArgumentParser(
description="Uber-tabs-to-spaces converter for Python source code.")
arg_parser.add_argument("filename", nargs=argparse.REMAINDER, help="file to process")
args = arg_parser.parse_args()
ret = 0
for filename in args.filename:
if not process_file(filename):
ret = 1
return ret
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment