查找iOS工程中未使用到方法脚本 FindSelectorsUnrefs.py

2024-05-15 10:18

本文主要是介绍查找iOS工程中未使用到方法脚本 FindSelectorsUnrefs.py,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

# coding:utf-8import os
import re
import sys
import getoptreserved_prefixs = ["-[", "+["]# 获取入参参数
def input_parameter():opts, args = getopt.getopt(sys.argv[1:], '-a:-p:-w:-b:',['app_path=', 'project_path=', 'black_list_Str', 'white_list_str'])black_list_str = ''white_list_str = ''white_list = []black_list = []# 入参判断for opt_name, opt_value in opts:if opt_name in ('-a', '--app_path'):# .app文件路径app_path = opt_valueif opt_name in ('-p', '--project_path'):# 项目文件路径project_path = opt_valueif opt_name in ('-b', '--black_list_Str'):# 检测黑名单前缀,不检测谁black_list_Str = opt_valueif opt_name in ('-w', '--white_list_str'):# 检测白名单前缀,只检测谁white_list_str = opt_valueif len(black_list_str) > 0:black_list = black_list_str.split(",")if len(white_list_str) > 0:white_list = white_list_str.split(",")if len(white_list) > 0 and len(black_list) > 0:print("\033[0;31;40m白名单【-w】和黑名单【-b】不能同时存在\033[0m")exit(1)# 判断文件路径存不存在if not os.path.exists(project_path):print("\033[0;31;40m输入的项目文件路径【-p】不存在\033[0m")exit(1)app_path = verified_app_path(app_path)if not app_path:exit('输入的app路径不存在,停止运行')return app_path, project_path, black_list, white_listdef verified_app_path(path):if path.endswith('.app'):appname = path.split('/')[-1].split('.')[0]path = os.path.join(path, appname)if appname.endswith('-iPad'):path = path.replace(appname, appname[:-5])if not os.path.isfile(path):return Noneif not os.popen('file -b ' + path).read().startswith('Mach-O'):return Nonereturn path# 获取protocol中所有的方法
def header_protocol_selectors(file_path):# 删除路径前后的空格file_path = file_path.strip()if not os.path.isfile(file_path):return Noneprotocol_sels = set()file = open(file_path, 'r', encoding='utf-8',errors='ignore')is_protocol_area = False# 开始遍历文件内容for line in file.readlines():# 删除注释信息# delete descriptionline = re.sub('\".*\"', '', line)# delete annotationline = re.sub('//.*', '', line)# 检测是否是 @protocol# match @protocolif re.compile('\s*@protocol\s*\w+').findall(line):is_protocol_area = True# match @endif re.compile('\s*@end').findall(line):is_protocol_area = False# match selif is_protocol_area and re.compile('\s*[-|+]\s*\(').findall(line):sel_content_match_result = None# - (CGPoint)convertPoint:(CGPoint)point toCoordinateSpace:(id <UICoordinateSpace>)coordinateSpaceif ':' in line:# match sel with parameters# 【"convertPoint:","toCoordinateSpace:"]sel_content_match_result = re.compile('\w+\s*:').findall(line)else:# - (void)invalidate;# match sel without parameters# invalidate;sel_content_match_result = re.compile('\w+\s*;').findall(line)if sel_content_match_result:# 方法参数拼接# convertPoint:toCoordinateSpace:funcList = ''.join(sel_content_match_result).replace(';', '')protocol_sels.add(funcList)file.close()return protocol_sels# 获取所有protocol定义的方法
def protocol_selectors(path, project_path):print('获取所有的protocol中的方法...')header_files = set()protocol_sels = set()# 获取当前引用的系统库中的方法列表system_base_dir = '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk'# get system librareislines = os.popen('otool -L ' + path).readlines()for line in lines:# 去除首尾空格line = line.strip()# /System/Library/Frameworks/MediaPlayer.framework/MediaPlayer (compatibility version 1.0.0, current version 1.0.0)# /System/Library/Frameworks/MediaPlayer.framework/MediaPlayer# delete description,line = re.sub('\(.*\)', '', line).strip()if line.startswith('/System/Library/'):# [0:-1],获取数组的左起第一个,到倒数最后一个,不包含最后一个,[1,-1)左闭右开library_dir = system_base_dir + '/'.join(line.split('/')[0:-1])if os.path.isdir(library_dir):# 获取当前系统架构中所有的类# 获取合集header_files = header_files.union(os.popen('find %s -name \"*.h\"' % library_dir).readlines())if not os.path.isdir(project_path):exit('Error: project path error')# 获取当前路径下面所有的.h文件路径header_files = header_files.union(os.popen('find %s -name \"*.h\"' % project_path).readlines())for header_path in header_files:# 获取所有查找到的文件下面的protocol方法,这些方法,不能用来统计header_protocol_sels = header_protocol_selectors(header_path)if header_protocol_sels:protocol_sels = protocol_sels.union(header_protocol_sels)return protocol_selsdef imp_selectors(path):print('获取所有的方法,除了setter and getter方法...')# return struct: {'setupHeaderShadowView':['-[TTBaseViewController setupHeaderShadowView]']}#  imp     0x100001260 -[AppDelegate setWindow:] ==>> -[AppDelegate setWindow:],setWindow:re_sel_imp = re.compile('\s*imp\s*0x\w+ ([+|-]\[.+\s(.+)\])')re_properties_start = re.compile('\s*baseProperties 0x\w{9}')re_properties_end = re.compile('\w{16} 0x\w{9} _OBJC_CLASS_\$_(.+)')re_property = re.compile('\s*name\s*0x\w+ (.+)')imp_sels = {}is_properties_area = False# “otool - ov”将输出Objective - C类结构及其定义的方法。for line in os.popen('/usr/bin/otool -oV %s' % path).readlines():results = re_sel_imp.findall(line)if results:#  imp     0x100001260 -[AppDelegate setWindow:] ==>> [-[AppDelegate setWindow:],setWindow:](class_sel, sel) = results[0]if sel in imp_sels:imp_sels[sel].add(class_sel)else:imp_sels[sel] = set([class_sel])else:# delete setter and getter methods as ivar assignment will not trigger them# 删除相关的set方法if re_properties_start.findall(line):is_properties_area = Trueif re_properties_end.findall(line):is_properties_area = Falseif is_properties_area:property_result = re_property.findall(line)if property_result:property_name = property_result[0]if property_name and property_name in imp_sels:# properties layout in mach-o is after func impimp_sels.pop(property_name)# 拼接set方法setter = 'set' + property_name[0].upper() + property_name[1:] + ':'# 干掉set方法if setter in imp_sels:imp_sels.pop(setter)return imp_selsdef ref_selectors(path):print('获取所有被调用的方法...')re_selrefs = re.compile('__TEXT:__objc_methname:(.+)')ref_sels = set()lines = os.popen('/usr/bin/otool -v -s __DATA __objc_selrefs %s' % path).readlines()for line in lines:results = re_selrefs.findall(line)if results:ref_sels.add(results[0])return ref_selsdef ignore_selectors(sel):if sel == '.cxx_destruct':return Trueif sel == 'load':return Truereturn Falsedef filter_selectors(sels):filter_sels = set()for sel in sels:for prefix in reserved_prefixs:if sel.startswith(prefix):filter_sels.add(sel)return filter_selsdef unref_selectors(path, project_path):# 获取所有类的protocol的方法集合protocol_sels = protocol_selectors(path, project_path)# 获取项目所有的引用方法ref_sels = ref_selectors(path)if len(ref_sels) == 0:exit('获取项目所有的引用方法为空....')# 获取所有的方法,除了set方法imp_sels = imp_selectors(path)print("\n")if len(imp_sels) == 0:exit('Error: imp selectors count null')unref_sels = set()for sel in imp_sels:# 所有的方法,忽略白名单if ignore_selectors(sel):continue# 如果当前的方法不在protocol中,也不再引用的方法中,那么认为这个方法没有被用到# protocol sels will not apppear in selrefs sectionif sel not in ref_sels and sel not in protocol_sels:unref_sels = unref_sels.union(filter_selectors(imp_sels[sel]))return unref_sels# 黑白名单过滤
def filtration_list(unref_sels, black_list, white_list):# 黑名单过滤temp_unref_sels = list(unref_sels)if len(black_list) > 0:# 如果黑名单存在,那么将在黑名单中的前缀都过滤掉for unref_sel in temp_unref_sels:for black_prefix in black_list:class_method = "+[%s" % black_prefixinstance_method = "-[%s" % black_prefixif (unref_sel.startswith(class_method) or unref_sel.startswith(instance_method)) and unref_sel in unref_sels:unref_sels.remove(unref_sel)break# 白名单过滤temp_array = []if len(white_list) > 0:# 如果白名单存在,只留下白名单中的部分for unref_sel in unref_sels:for white_prefix in white_list:class_method = "+[%s" % white_prefixinstance_method = "-[%s" % white_prefixif unref_sel.startswith(class_method) or unref_sel.startswith(instance_method):temp_array.append(unref_sel)breakunref_sels = temp_arrayreturn unref_sels# 整理结果,写入文件
def write_to_file(unref_sels):file_name = 'selector_unrefs.txt'f = open(os.path.join(sys.path[0].strip(), file_name), 'w')unref_sels_num_str = '查找到未被使用的方法: %d个\n' % len(unref_sels)print(unref_sels_num_str)f.write(unref_sels_num_str)num = 1for unref_sel in unref_sels:unref_sels_str = '%d : %s' % (num, unref_sel)print(unref_sels_str)f.write(unref_sels_str + '\n')num = num + 1f.close()print('\n项目中未使用方法检测完毕,相关结果存储到当前目录 %s 中' % file_name)print('请在项目中进行二次确认后处理')if __name__ == '__main__':# 获取入参app_path, project_path, black_list, white_list = input_parameter()# 获取未使用方法unref_sels = unref_selectors(app_path, project_path)# 黑白名单过滤unref_sels = filtration_list(unref_sels, black_list, white_list)# 打印写入文件write_to_file(unref_sels)

网上找了几个脚本都有问题,以上是自己修改后测试可以使用的。

使用示例:

python3 FindSelectorsUnrefs.py -a /Users/XXXXXX/Library/Developer/Xcode/DerivedData/XWorld-bhzlzkolmmftbubftspqdqfxqzpo/Build/Products/Debug-iphoneos/XXX.app -p /Users/XXXXX/Documents/GitHub/XXXXXX/XXXXX

运行成功后会在当前目录下生成 selector_unrefs.txt文件 里面是工程中未使用到的方法

先cd到脚本路路径

1. python3 表示使用的python版本

2. FindSelectorsUnrefs.py 表示要执行的文件

3. -a XXXXXXXX 代表需要分析的工程文件中生成的.app路径 在Products的xxxx.app里 Show In Finder可以查看

4. -p 表示工程文件所在的路径

其他扩展参数说明:-w 结果白名单处理,检测结果,只想要以什么开头的类的方法,多个用逗号隔开,比如JD,BD,AL

-b 结果黑名单处理,检测结果,不想要以什么开头的类的方法,多个用逗号隔开,比如Pod,AF,SD

-w 和 -b 不能共存,共存会报错

这篇关于查找iOS工程中未使用到方法脚本 FindSelectorsUnrefs.py的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/991549

相关文章

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

C#中Guid类使用小结

《C#中Guid类使用小结》本文主要介绍了C#中Guid类用于生成和操作128位的唯一标识符,用于数据库主键及分布式系统,支持通过NewGuid、Parse等方法生成,感兴趣的可以了解一下... 目录前言一、什么是 Guid二、生成 Guid1. 使用 Guid.NewGuid() 方法2. 从字符串创建

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四: