Created
August 15, 2023 03:53
-
-
Save nyteshade/4eaf59298a1065ebf8f79829a30f93fa to your computer and use it in GitHub Desktop.
Python Codemod to Modify All Indentation from 4 to 2 Spaces, Recursively, In a Directory
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
import os | |
import sys | |
def modify_indentation(code): | |
new_code_lines = [] | |
for line in code.splitlines(): | |
leading_spaces = 0 | |
# Count the leading spaces in increments of 4 | |
while leading_spaces + 4 <= len(line) and line[leading_spaces:leading_spaces + 4] == ' ': | |
leading_spaces += 4 | |
# Count the leading tabs | |
leading_tabs = 0 | |
while leading_tabs < len(line) and line[leading_tabs] == '\t': | |
leading_tabs += 1 | |
# Calculate total indentation and convert to 2 spaces per level | |
total_indentation = (leading_spaces // 4 + leading_tabs) * 2 | |
new_line = ' ' * total_indentation + line[leading_spaces + leading_tabs:] | |
new_code_lines.append(new_line) | |
return '\n'.join(new_code_lines) | |
def process_directory(directory): | |
for root, dirs, files in os.walk(directory): | |
if '.git' in dirs: | |
dirs.remove('.git') | |
for file in files: | |
if file.endswith('.py'): | |
file_path = os.path.join(root, file) | |
with open(file_path, 'r', encoding='utf-8') as f: | |
code = f.read() | |
new_code = modify_indentation(code) | |
with open(file_path, 'w', encoding='utf-8') as f: | |
f.write(new_code) | |
print(f"Processed file: {file_path}") | |
if __name__ == "__main__": | |
directory = sys.argv[1] | |
if os.path.isdir(directory): | |
process_directory(directory) | |
print("Processing completed successfully.") | |
else: | |
print("Invalid directory path. Please provide a valid directory.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment