iOS项目清除没有使用的图片

前言

iOS项目一般将图片放到Image Assets中管理图片,迭代几个版本后,有些图片不一定能及时删除,这些图片会让项目的体积变大,所以需要定时清理。Android可以使用Lint完成这个任务,iOS可以使用Python脚本轻松做到。

一、安装工具The Silver Searcher

The Silver Searcher Git地址:https://github.com/ggreer/the_silver_searcher
使用命令安装,在终端输入命令:

brew install the_silver_searcher

二、Python脚本

执行脚本:

python cleanImage.py

脚本思路是这样的:
1、获取所有图片的路径和图片名字;
2、根据图片名字搜索工程中的代码,判断是否用到这个图片的名字。
3、如果图片没有在代码中使用,则删除。

全部脚本如下:

# 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匹配一个数字字符,等价于[0-9]。 +匹配1或者多个正好在它之前的那个字符。
images = glob.glob('/Users/tianxiawoyougood/Git/SourceTree/hwmc/ios_hwmc_project/hwmc_ios_project/newhwmc/Resource/*.xcassets/*.imageset') # 搜索所有文件获得图片路径 注意:使用绝对路径
print 'image数量:'
print len(images)

def find_un_used():
    
    # os.path.basename(pic) pic是路径,返回路径最后的文件名。例如:os.path.basename('c:\\test.csv') 返回:test.csv
    # [expt for pic in images] 是列表生成器。以pic为值,进行expt,生成的值组成一个数组。
    img_names = [os.path.basename(pic)[:-9] for pic in images]
    unused_imgs = []
    
    # 遍历所有图片
    for i in range(0, len(images)):
        pic_name = img_names[i]
        print '遍历图片:'
        print pic_name
        
        # 忽略的文件略过
        if is_ignore(pic_name):
            continue
        
        # 使用the_silver_searcher工具的ag命令查找代码中是否有使用这个名字。
        command = 'ag --ignore-dir %s "%s" %s' % (path ,pic_name, ignore_dir_path)
        result = os.popen(command).read()
        
        # 没有找到。删除
        if result == '':
            unused_imgs.append(images[i])
            print '删除图片:'
            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) 判断是否ignore在str中,并且在开头位置。
            return True
    return False


if __name__ == '__main__':
    find_un_used()

Done!

你可能感兴趣的:(发布)