Created
September 15, 2021 13:07
-
-
Save TheRealJokerMan/6cfae5918dbbf2e781e4046f3c19cc5c to your computer and use it in GitHub Desktop.
Convert tabs to spaces and remove trailing whitespace in code files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python3 | |
import argparse | |
import functools | |
import multiprocessing | |
import pathlib | |
import os | |
import sys | |
def _gather_file_list(path: str, patterns: list): | |
files = [] | |
for pattern in patterns: | |
files.extend(pathlib.Path(path).rglob(pattern)) | |
return files | |
def _parse_arguments(): | |
parser = argparse.ArgumentParser( | |
prog='tabs-to-spaces', | |
description='Convert tabs to spaces.') | |
parser.add_argument('--tab-width', | |
dest='tab_width', | |
default=4, | |
help='Number of spaces used to replace a tab.') | |
parser.add_argument('--trim-eol', | |
dest='trim_eol', | |
default=True, | |
help='Determines if trailing whitespace should be removed.') | |
parser.add_argument('--patterns', | |
dest='pattern_list', | |
nargs='+', | |
default=[], | |
help='List of file pattern to process..') | |
parser.add_argument('--directory', | |
dest='directory', | |
type=str, | |
help='Directory to process.') | |
args = parser.parse_args() | |
if not args.directory or not args.pattern_list: | |
parser.print_help(sys.stderr) | |
return None | |
else: | |
args.directory = os.path.abspath(args.directory) | |
print('Settings:') | |
print('\tTab width : ', args.tab_width) | |
print('\tTrim lines: ', args.trim_eol) | |
print('\tPatterns : ', args.pattern_list) | |
print('\tDirectory : ', args.directory) | |
return args | |
def _process_file(path: str, tab_width: int, trim: bool): | |
contents = None | |
with open(path, 'r') as in_file: | |
contents = in_file.readlines() | |
if contents: | |
for line in contents: | |
line = line.replace('\t', ' ' * tab_width) | |
if trim: | |
line = line.rstrip() | |
with open(path, 'w') as out_file: | |
out_file.writelines(contents) | |
def main(): | |
args = _parse_arguments() | |
if not args: | |
return -1 | |
file_list = _gather_file_list(args.directory, args.pattern_list) | |
if not file_list: | |
return -1 | |
with multiprocessing.Pool() as pool: | |
pool.map(functools.partial(_process_file, | |
tab_width=args.tab_width, | |
trim=args.trim_eol), | |
file_list) | |
return 0 | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment