# coding=utf-8
import os
import re
def file_split(split_url):
import os
(parent_path, file_name) = os.path.split(split_url)
(shot_name, extension) = os.path.splitext(file_name)
if split_url.endswith('.9.png'):
return parent_path, file_name, file_name.split(".")[0], '.9.png'
else:
return parent_path, file_name, shot_name, extension
def check_file_ignore(_file, _check_file_list):
file_ignore = True
for ignore_file in _check_file_list:
new_file_req = ignore_file.replace('*', r'(.*)')
if ignore_file in _file:
file_ignore = False
elif len(re.findall(new_file_req, _file.replace('.', r'\.'))) > 0:
file_ignore = False
return file_ignore
def is_code_unused(_file_shot_name, _check_file_list) -> bool:
_r_string1 = '.' + _file_shot_name # import a.b.Str
_r_string2 = ' ' + _file_shot_name # : Str
_r_string3 = _file_shot_name + ':' # Str::class.java
_r_string4 = ':' + _file_shot_name # str: Str
_r_string5 = _file_shot_name + '.' # Str.java
_r_string6 = '(' + _file_shot_name # (Str
_r_string7 = _file_shot_name + ')' # Str)
for _root, _, _files in os.walk(tar_dir):
if (os.sep + "src" + os.sep) not in _root:
continue
for _file in _files:
if check_file_ignore(_file, _check_file_list):
continue
if file_split(_file)[2] == _file_shot_name:
continue
_check_file_path = os.path.join(_root, _file)
with open(_check_file_path, encoding='utf-8') as f:
_content = f.read()
if (_r_string2 in _content
or _r_string3 in _content
or _r_string4 in _content
or _r_string5 in _content
or _r_string6 in _content
or _r_string7 in _content
or _r_string1 in _content):
# 该文件被其他文件引用了
return False
return True
tar_dir = os.getcwd() + os.sep + "app"
check_ref_files = ['*.java', '*.kt', "*.xml"]
check_remove_files = ['*.java', '*.kt']
if __name__ == '__main__':
for root, dirs, files in os.walk(tar_dir):
if (os.sep + "src" + os.sep) not in root:
continue
for file in files:
if check_file_ignore(file, check_remove_files):
continue
file_path = os.path.join(root, file)
is_unused = is_code_unused(file_split(file)[2], check_ref_files)
if is_unused:
print(f'remove {file_path}')
# os.remove(file_path)
Apk瘦身脚本 - 无用代码剔除
于 2024-04-03 10:44:53 首次发布
本文介绍了一个Python函数,用于检查源代码文件是否被其他文件引用,如果某文件未被引用,将被标记为可删除。主要涉及文件路径操作、正则表达式匹配和目录遍历。
276

被折叠的 条评论
为什么被折叠?



