Skip to content

Instantly share code, notes, and snippets.

@dcwatson
Last active April 16, 2018 15:57
Show Gist options
  • Save dcwatson/5034116 to your computer and use it in GitHub Desktop.
Save dcwatson/5034116 to your computer and use it in GitHub Desktop.
A quick script to run through files in a directory changing leading tabs to spaces, trimming trailing whitespace, and converting line endings to UNIX (LF).
#!/usr/bin/env python
import argparse
import fnmatch
import os
import sys
DEFAULT_EXTENSIONS = ['py', 'css', 'html', 'js', 'txt', 'json', 'sh', 'sql', 'yml', 'yaml', 'xml']
def fix_line(line, opts):
line = line.rstrip()
if not line:
return line
tabs = 0
spaces = 0
for ch in line:
if ch == '\t':
tabs += 1
spaces = 0
elif ch == ' ':
spaces += 1
if spaces == opts.spaces:
tabs += 1
spaces = 0
else:
break
indent = (tabs * opts.spaces) + spaces
return ' ' * indent + line.lstrip()
def fix_file(path, opts):
for exclude in opts.exclude:
if fnmatch.fnmatch(path, exclude):
return
if os.path.splitext(path)[1][1:] not in opts.ext:
return
print(path)
if opts.dry_run:
return
lines = [fix_line(line, opts) for line in open(path, 'r')]
data = '\n'.join(lines).strip()
with open(path, 'w') as f:
f.write(data)
if data:
f.write('\n')
def fix_directories(opts):
for path in opts.dirs:
if os.path.isfile(path):
fix_file(os.path.abspath(path), opts)
else:
for root, dirs, files in os.walk(path):
for name in files:
if name.startswith('.'):
continue
fix_file(os.path.join(root, name), opts)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Replaces leading tabs with spaces, and fixes line endings.')
parser.add_argument('-s', '--spaces', type=int, default=4)
parser.add_argument('-e', '--ext', action='append')
parser.add_argument('-x', '--exclude', action='append', default=[])
parser.add_argument('-n', '--dry-run', action='store_true', default=False)
parser.add_argument('dirs', nargs='+')
opts = parser.parse_args()
if not opts.ext:
opts.ext = DEFAULT_EXTENSIONS
fix_directories(opts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment