0、前言
最近在研究 iOS 包瘦身、提升编译速度的策略。
无用
Pod 依赖,是容易被忽略的一个可优化点,去掉无用依赖,一方面可以
降低包大小
,另一方面也能
加快编译速度
。
然鹅!!!这么一个朴素而常见的需求,搜遍全网却
没有
发现好的轮子!于是抽空自己造了一个~
1、检查脚本
使用Python开发检查脚本,原理如下:
- 首先扫描所有工程中import的头文件,存入 allImportedFiles set 集合中;
- 扫描工程 podspec 文件,找到所有依赖的pod名,存入 allPodNames 数组中;
- 遍历 allPodNames 数组,根据 pod 名,和所有 pods 的存放路径,拼接得到该 pod 对应的文件路径 podPath。扫描 podPath 路径,获得路径下的所有文件,存入 filesInPod set 集合中,并判断:
- 如果 filesInPod 为空,即未搜索到 podPath 路径或 podPath 内无文件,则存入 unfindPods set 集合中;
- 如果 filesInPod 不为空,且和 allImportedFiles 的交集为空,则说明该 pod 的文件没有在工程中用到,则将该 pod 存入 unusedPods set 集合中;
- 遍历 allPodNames 结束后,从 unusedPods 中减去白名单文件;
- 输出 unusedPods (无用依赖 pod)与 unfindPods(未找到 pod 文件)。
【注意】
- 如果检测到 unfindPods 较多,说明传入的 pods 存放路径可能有问题。
核心代码(完整代码可以在文末连接内查看):
# 所有项目中引入的头文件
allImportedFiles = {os.path.splitext(os.path.basename(fileName))[0] for fileName in getImportedFiles(scanCodePaths, *scanExtension)}
# 所有依赖的 Pod
allPodNames = [podName for podName in getDependenciedPodNames(podspecPaths)]
unusedPods = set()
unusedPodFileCount = 0
totalPodFileCount = 0
unfindPods = set()
for podName in allPodNames:
for scanPodPath in scanPodPaths:
podPath = os.path.join(scanPodPath, podName)
# pod 的各个文件
filesInPod = {os.path.splitext(os.path.basename(fileName))[0] for fileName in getFileNames(podPath, *scanExtension)}
totalPodFileCount += len(filesInPod)
if not filesInPod:
unfindPods.add(podName)
elif not allImportedFiles & filesInPod:
# 两者无交集,则 pod 是无用依赖
unusedPods.add(podName)
unusedPodFileCount += len(filesInPod)
unusedPods -= whiteList # 白名单
if unusedPods:
print '//======================= 无用依赖 ========================//'
print '总依赖 pod ' + str(len(allPodNames)) + '个'
print '无用依赖 pod ' + str(len(unusedPods)) + '个:'
for pod in unusedPods:
print pod
print '未找到 pod 文件 ' + str(len(unfindPods)) + '个:'
for pod in unfindPods:
print pod
print '总 pod 依赖文件数:' + str(totalPodFileCount)
print '总无用 pod 依赖文件数:' + str(unusedPodFileCount)
else:
print "恭喜~~ 没有无用pod依赖!"
2、结果
命令行输入:
python scanUnusedPod.py --codes /Users/liqiyu/Work/code/DeliciousFood/Classes --pods /Users/liqiyu/Work/code/iphone-nova/Nova/Pods --podspec /Users/liqiyu/Work/code/DeliciousFood/DeliciousFood.podspec
输出:
脚本检测出工程共有 59 个 Pod 依赖,其中 4 个(NVWebView、Tuan、YapDatabase、NVSound)为无用依赖,1 个(NVServices)为未找到 pod 文件。
查看 NVServices pod 后发现,该 pod 已被废弃,里面只有一个空的 README.md 文件。
3、完整代码
求 Star~~
求 Star~~
求 Star~~
Github 地址:https://github.com/Jlaix/scanUnusedPod