
本文作者:伯樂在線 - 姜家志
項目經過多次需求變更與產品迭代,總會沉澱下一批再也用不到的圖片。這些資源一方面讓圖片目錄結構變得混亂,另一方面會直接推高上線後 ipa 包的體積。Android 上可以用 Lint 輕鬆完成這件事,iOS 卻缺少趁手的官方工具,因此我參考網上的思路,寫了一個 Python 腳本來清理 Xcode 項目中未使用的圖片資源。
iOS 用 Images.xcassets 管理圖片,每張圖對應一個 *.imageset 目錄,裡面放 1x、2x、3x 三種倍圖以及一個 Contents.json 描述文件。要清除某張圖,就是把對應的 .imageset 目錄刪掉。
代碼中引用圖片一般是:
[UIImage imageNamed:@"image"];
而在 xib 中,圖片以 XML 屬性的形式出現:
<imageView image="image" id="Rb9-sl-eQM"/>
所以判斷思路很簡單:遍歷項目中的所有文件,如果某個圖片名(name)能被搜到,說明它在被使用;搜不到就可以清理。
搜索文件內容可以用 grep 或 ack,但有更快更好的選擇:The Silver Searcher,項目地址 https://github.com/ggreer/the_silver_searcher。它使用方便,速度更快,語法也更簡單。
安裝:
brew install the_silver_searcher
使用 ag 搜索:
ag "image" './'
這條命令會搜索當前目錄及其所有子目錄中包含 image 的文件。
搜索與刪除都可以交給 bash,而 Python 能直接執行 shell 命令。
os.popen('echo $PATH')
執行命令,並通過 .read() 拿到輸出結果:
os.popen('echo $PATH').read()
也可以直接執行:
os.system('rm -rf dir')
核心用到兩條命令:ag "image" './' 負責搜索,rm -rf './' 負責刪除目錄。
import glob
import os
path = 'ios'
images = glob.glob('ios/images.xcassets/*/*.imageset')
def find_un_used():
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]
command = 'ag "%s" %s' % (pic_name, path)
result = os.popen(command).read()
if result == '':
unused_imgs.append(images[i])
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!')
這段代碼從當前文件夾找出所有 .imageset,去掉後綴拿到純文件名,再到項目目錄裡搜索該名稱是否被引用,未被引用的直接刪除,並把清單寫入 unused.txt 方便覆核。
不過實際跑一遍會發現,有些並不該刪的圖片也被清掉了。原因是漏了一種例外情況。
有些時候我們會動態給控件賦值,例如:
for (int i = 1; i < count; i++) {
NSString *name = [NSString stringWithFormat:@"image_%d", i];
[button setImage:[UIImage imageNamed:name]];
}
這種寫法下,搜索 image_1 時找不到字面引用,腳本就會誤刪,但這張圖其實是被使用的。
解法是預先準備一個 ignore 列表,用正則表達式描述需要跳過的命名:
ignores = {r'image_\d+'}
再定義一個判斷函數:
import re
def is_ignore(str):
for ignore in ignores:
if re.match(ignore, str):
return True
return False
文件名命中 ignore 規則時就跳過清理。
Python 源碼地址:https://github.com/jjz/script/blob/master/un_used.py
使用前請自行修改腳本中的目錄配置,然後執行:
python un_used.py
最後提醒一句:刪除操作不可逆,建議先提交一次代碼,或者先只跑搜索、把 unused.txt 拿出來人工覆核一遍,確認無誤再執行刪除,會穩妥得多。