Preface
iOS projects usually put pictures into Image Assets to manage pictures. After iterating several versions, some pictures may not be deleted in time. These pictures will make the project larger, so they need to be cleaned regularly. Android can do this using Lint, and iOS can easily do it using Python scripts.
1, Installation tool The Silver Searcher
The Silver Searcher Git address: https://github.com/ggreer/the_silver_searcher
Using command installation, enter the command at the terminal:
brew install the_silver_searcher
2, Python script
Execute script:
python cleanImage.py
The script idea is as follows:
1. Get the path and name of all pictures;
2. Search the code in the project according to the picture name, and judge whether to use the picture name.
3. If the picture is not used in the code, delete it.
The whole script is as follows:
# coding=utf-8 import glob import os import re import shutil import time path = '/Users/tianxiawoyougood/Git/SourceTree/hwmc/ios_hwmc_project/hwmc_ios_project/newhwmc' ignore_dir_path = '/Users/tianxiawoyougood/Git/SourceTree/hwmc/ios_hwmc_project/hwmc_ios_project/newhwmc/Resource/' ignores = {r'image_\d+'} # \d matches a numeric character, equivalent to [0-9]. +Match 1 or more characters exactly before it. images = glob.glob('/Users/tianxiawoyougood/Git/SourceTree/hwmc/ios_hwmc_project/hwmc_ios_project/newhwmc/Resource/*.xcassets/*.imageset') # Search all files to get picture path note: use absolute path print 'image Number:' print len(images) def find_un_used(): # os.path.basename(pic) pic is the path, which returns the last filename of the path. For example: os.path.basename('c:\test.csv ') Returns: test.csv # [expt for pic in images] is a list generator. Take pic as the value, expand, and the generated value forms an array. img_names = [os.path.basename(pic)[:-9] for pic in images] unused_imgs = [] # Traverse all pictures for i in range(0, len(images)): pic_name = img_names[i] print 'Traversal picture:' print pic_name # Ignored files skipped if is_ignore(pic_name): continue # Use the ag command of the silver searcher tool to find out if the name is used in the code. command = 'ag --ignore-dir %s "%s" %s' % (path ,pic_name, ignore_dir_path) result = os.popen(command).read() # Can't find. delete if result == '': unused_imgs.append(images[i]) print 'Delete picture:' print 'remove %s' % (images[i]) os.system('rm -rf %s' % (images[i])) text_path = 'unused.txt' tex = '\n'.join(sorted(unused_imgs)) os.system('echo "%s" > %s' % (tex, text_path)) print 'unuse res:%d' % (len(unused_imgs)) print 'Done!' def is_ignore(str): for ignore in ignores: if re.match(ignore, str): # re.match(ignore,str) determines whether ignore is in str and at the beginning. return True return False if __name__ == '__main__': find_un_used()
Done!