前言
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!