Last active
May 9, 2020 18:20
-
-
Save remzmike/9ecb7b85a5a7c8d642c21a611855ff7d to your computer and use it in GitHub Desktop.
quick replace leading spaces with tabs
This file contains 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
import os | |
import time | |
dirnames = ['classes', 'triggers'] | |
timestamp = '%s' % time.time() | |
for dirname in dirnames: | |
for fname in os.listdir(dirname): | |
fpath = os.path.join(dirname, fname) | |
# skip dirs | |
if os.path.isdir(fpath): | |
continue | |
# skip wrong files | |
is_filename_valid = fname.lower().endswith('.cls') or fname.lower().endswith('.trigger') | |
is_filename_valid = is_filename_valid and not fname.lower().endswith('test.cls') | |
if not is_filename_valid: | |
continue | |
# valid paths are printed | |
print fpath | |
f = open(fpath) | |
new_lines = [] | |
for line in f.readlines(): | |
# count leading whitespace | |
whitespace_count = 0 | |
for i, char in enumerate(line): | |
if char == ' ': | |
whitespace_count = whitespace_count + 1 | |
elif char == '\t': | |
whitespace_count = whitespace_count + 4 | |
else: | |
break | |
rest_of_line = line[i:] | |
tab_count, space_count = divmod(whitespace_count, 4) | |
new_line = '\t' * tab_count + ' ' * space_count + rest_of_line | |
#print repr(new_line) | |
new_lines.append(new_line) | |
out_dirname = os.path.join(dirname, 'with-tabs.' + timestamp) | |
if not os.path.exists(out_dirname): | |
os.mkdir(out_dirname) | |
out_fpath = os.path.join(out_dirname, fname) | |
out_file = open(out_fpath, 'wb') # i hate text mode in python 2 iirc | |
out_file.writelines(new_lines) | |
out_file.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment