Last active
March 17, 2025 15:12
-
-
Save codiini/6366d458df6fd888e525bc51735f7cae to your computer and use it in GitHub Desktop.
A python script to find unused assets in your codebase, list them and delete them if the prompt is accepted
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 re | |
def find_unused_images(asset_dir, code_dir): | |
# Collect all image files (common extensions: jpg, png, gif, svg, webp) | |
image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.svg', '.webp') | |
images = [os.path.join(dp, f) for dp, dn, filenames in os.walk(asset_dir) for f in filenames if f.lower().endswith(image_extensions)] | |
unused_images = [] | |
for image in images: | |
image_name = os.path.basename(image) # Get the image file name | |
found = False | |
# Search for the image file name in the code directory | |
for dp, dn, filenames in os.walk(code_dir): | |
for file in filenames: | |
# Check relevant file types | |
if file.endswith(('.html', '.md', '.css', '.liquid', '.php')): | |
with open(os.path.join(dp, file), 'r', encoding='utf-8') as f: | |
if re.search(re.escape(image_name), f.read()): | |
found = True | |
break | |
if found: | |
break | |
# If the image is not found in any file, consider it unused | |
if not found: | |
unused_images.append(image) | |
return unused_images | |
# Paths to your assets and code directories | |
image_dir = './source' | |
code_dir = './build' | |
# Find unused images | |
unused_images = find_unused_images(image_dir, code_dir) | |
# Print the list of unused images | |
print("Unused images:") | |
for img in unused_images: | |
print(img) | |
# Confirm deletion | |
if unused_images: | |
delete = input("\nDo you want to delete these unused images? (yes/no): ").strip().lower() | |
if delete == 'yes': | |
for img in unused_images: | |
try: | |
os.remove(img) | |
print(f"Deleted: {img}") | |
except Exception as e: | |
print(f"Failed to delete {img}: {e}") | |
else: | |
print("No files were deleted.") | |
else: | |
print("No unused images found.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Javascript version