清理IOS项目未使用图片脚本

项目经过需求的变更,产品迭代,会经过多次的改版,有些以前不再使用的图片不一定能够及时的清理掉,这些无用的图片一方面让项目图片资源的结构更加的复杂,另一方面会导致ipa包的体积变大。

因此我们需要清理不再使用的图片资源,在Android项目中使用Lint可以轻松的完成这个任务,iOS中没有太好的工具,借助网上的资源编写了个Python脚本。

 

安装Silver Searcher来搜索字符串,使用方法和ack,grep相似,而且搜索速度比ack,grep快。使用命令行安装:

//先安装homebrew
ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

//再安装Silver Searcher
brew install the_silver_searcher

 

可以使用ag、base命令等

ag "image" './'

os.popen('echo $PATH')

//执行bash命令,可以通过os.popen('echo $PATH').read()读取执行的结果。

需要用到的bash命令是ag "image" './'rm -rf './',后者用来删除文件夹。

 

ignores

可能使用下面的方式来访问图片

for (int i = 1; i <= 10; ++i) {
    NSString *imageName = [NSString stringWithFormat:@"image_%d", i];
    UIImage *image = [UIImage imageNamed:imageName];
    ......
}

因此image_1这样的图片会被脚本给检查为未使用,因此添加了ignores过滤器,包含到此内容中的图片会被忽略掉。

ignores = {r'image_\d+', r'RLineTravelType\d+', r'address_\d+'}

def is_ignore(str):
    for ignore in ignores:
        #print ignore, re.match(ignore, str)
        if re.match(ignore, str):
            return True

    print "False"
    return False

 

完整代码如下unUserImg.py

# -*- coding : utf-8 -*-

import os
import glob
import re


ignores = {r'image_\d+', r'RLineTravelType\d+', r'address_\d+'}

pathI = '/adu/WorkSpaceN/QunarRN/car_rn/CarBundle/Images'

def find_un_used():
    pics = glob.glob1(pathI, '*.png')
    pics = [pic[:-4].replace('@2x', '') for pic in pics]
    print "pnames: ====================>>>>>>>>>>>>>>>"
    print pics
    print "pnames: <<<<<<<<<<<<<<<===================="

    path = '/adu/WorkSpaceN/QunarRN/car_rn/Car'
    unused_pics = []
    for pic_name in set(pics):
        if is_ignore(pic_name) == False:
            command = 'ag "%s" %s'%(pic_name, path)
              result = os.popen(command).read()
              if result == '':
                  unused_pics.append(pic_name)
                  #os.system('rm -rf %s' % (pic_name))
          
            
    txt_path = 'pics.txt'
    txt = '\n'.join(sorted(unused_pics))
    os.system('echo "%s" > %s'%(txt, txt_path))

    print 'Done!!!!!'


def is_ignore(str):
    for ignore in ignores:
        #print ignore, re.match(ignore, str)
        if re.match(ignore, str):
            return True

    print "False"
    return False


def doRm():
    path = '/adu/WorkSpaceN/QunarRN/car_rn/Car'

    txt_path = 'pics.txt'
    pics = open(txt_path).readlines()

    for pic in pics:
        pic = pic.strip('\n')
          sd_pic = path + pic + '.png'
          hd_pic = path + pic + '@2x.png'
      
          os.system('rm "%s"'%sd_pic)
          os.system('rm "%s"'%hd_pic)

    print 'rn Done!'

if __name__ == '__main__':
    find_un_used()
    #is_ignore('image3')


    
def read_file(path):
    print "read file path:", path
    path = os.path.normpath(path)
    if not os.path.exists(path):
        print("文件路径不存在")
        sys.exit(1)

    img_names = []
     for line in open(path):
         # print line
         # print (line.strip())
         img_names.append((line.strip()))
     # print img_names
     return img_names

#查找hybrid项目中是否有使用未使用的图片
def find_hy_un_used():
    #read file name
    img_names = read_file('/adu/WorkSpaceN/QunarRN/car_rn/Car/pics.txt')
    # print img_names

     path = '/adu/QunarGitlab/yexuxianGit/FECar/hybrid_fe/h5/src'
    unused_pics = []
    for pic_name in set(img_names):
        print pic_name
        command = 'ag "%s" %s'%(pic_name, path)
          result = os.popen(command).read()
          if result == '':
              unused_pics.append(pic_name)

    txt_path = 'hypics.txt'
    txt = '\n'.join(sorted(unused_pics))
    print txt
    os.system('echo "%s" > %s'%(txt, txt_path))
    print "Done ..."

# copy指定文件夹下的文件到新的文件夹中
def sourcecpy():
    srcFilePath = '/adu/WorkSpaceN/QunarRN/car_rn/Car/all_unused_pics.txt'
    img_names = read_file(srcFilePath)
    # print img_names

    srcFolderPath = '/adu/WorkSpaceN/QunarRN/car_rn/CarBundle/Images/'
    desFolderPath = '/adu/WorkSpaceN/QunarRN/car_rn/Car/unusedFiles/'
    for name in img_names:
        source = srcFolderPath+name
        # print source
        # shutil.copy2(source, desFolderPath)   #第一个参数是文件,第二个参数目录
        targetFile = os.path.join(desFolderPath,  name)
        print targetFile
        open(targetFile, "wb").write(open(source, "rb").read())
    print "Done ..."

#筛选出真正的文件名,@2x等
def findAll():
    srcFilePath = '/adu/WorkSpaceN/QunarRN/car_rn/Car/hypics.txt'
    img_names = read_file(srcFilePath)

    unused_pics = []
    for file in img_names:
        pics = glob.glob1('/adu/WorkSpaceN/QunarRN/car_rn/CarBundle/Images', file+'*')
        unused_pics.extend(pics)

    txt_path = 'all_unused_pics.txt'
    txt = '\n'.join(sorted(unused_pics))
    os.system('echo "%s" > %s'%(txt, txt_path))

    print 'Done!!!!!'

 

 

直接在命令行执行: #python unUserImg.py 即可

posted @ 2016-09-12 16:44  adler  阅读(941)  评论(0编辑  收藏  举报