Skip to content

Instantly share code, notes, and snippets.

@chrsp
Last active September 21, 2023 11:49
Show Gist options
  • Save chrsp/69ec149f06c7b78ccc6455d4970ce7f6 to your computer and use it in GitHub Desktop.
Save chrsp/69ec149f06c7b78ccc6455d4970ce7f6 to your computer and use it in GitHub Desktop.
Use to remove duplicate imports in Swift Files
import os
import re
import sys
def find_swift_files(directory):
swift_files = []
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(".swift"):
swift_files.append(os.path.join(root, file))
return swift_files
def remove_duplicate_imports(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
imports = set()
new_lines = []
for line in lines:
if line.startswith("import "):
# Check if the import statement has already been encountered
if line not in imports:
imports.add(line)
new_lines.append(line)
else:
new_lines.append(line)
with open(file_path, 'w') as file:
file.writelines(new_lines)
def main(directory):
swift_files = find_swift_files(directory)
for file in swift_files:
remove_duplicate_imports(file)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python remove_duplicate_imports.py <directory_path>")
sys.exit(1)
directory_to_scan = sys.argv[1]
main(directory_to_scan)
print("Duplicate imports removed successfully.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment