使用python 和 lint 删除项目无用资源的方法


Posted in Python onDecember 20, 2017

有部分老项目是在Eclipse环境开发的,最近公司要求应用瘦身,老项目也在其中。如果在 AS 下开发就不会有这样的问题,但是在 Eclipse 中就不太方便了,于是就写了这个脚本。第一次用Python写东西,代码里可能会有许多 Java、C 这样的痕迹,见谅。

使用方法

将 python 目录下的 delUnused.py 放到项目目录下,然后直接运行即可。

代码说明

利用lint进行代码审查

lint --check UnusedResources --xml [resultPath] [projectPath]

命令含义是检查项目中未使用的资源文件,并且用xml格式输出结果,需要提供检查结果输出的路径和项目路径。在脚本中已经自动提供了。

def exec_lint_command():
 cmd = 'lint --check UnusedResources --xml %s %s' % (_get_lint_result_path(), _get_project_dir_path())
 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
 c = p.stdout.readline().decode()
 while c:
  print(c)
  c = p.stdout.readline().decode()

这里给一个检查结果实例吧

<issue
  id="UnusedResources"
  severity="Warning"
  message="The resource `R.layout.activity_all_player` appears to be unused"
  category="Performance"
  priority="3"
  summary="Unused resources"
  explanation="Unused resources make applications larger and slow down builds."
  errorLine1="<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
"
  errorLine2="^"
  quickfix="studio">
  <location
   file="res\layout\activity_all_player.xml"
   line="2"
   column="1"/>
 </issue>

我们能用到的信息有 id message location 等。

解析检查结果

我是利用 minidom 解析的,具体的解析方法不多说,参考。

获取根节点

def _parse_lint_report():
 file = minidom.parse(_get_lint_result_path())
 root = file.documentElement
 beans = _parse_xml(root)
 return beans

解析第一层子节点

def _parse_xml(element, beans=None):
 if beans is None:
  beans = []
 for node in element.childNodes:
  if node.nodeName == ISSUE_KEY and node.nodeType is node.ELEMENT_NODE:
   lint_bean = _LintBean()
   lint_bean.id = node.getAttribute(ID_KEY)
   lint_bean.severity = node.getAttribute(SEVERITY_KEY)
   lint_bean.message = node.getAttribute(MESSAGE_KEY)
   _parse_location(node, lint_bean)
   lint_bean.print()
   beans.append(lint_bean)
 return beans

解析location 子节点

def _parse_location(node, bean):
 if not node.hasChildNodes():
  return
 for child in node.childNodes:
  if child.nodeName == LOCATION_KEY and node.nodeType is node.ELEMENT_NODE:
   bean.location.file = child.getAttribute(LOCATION_FILE_KEY)
   bean.location.line = child.getAttribute(LOCATION_LINE_KEY)
   bean.location.column = child.getAttribute(LOCATION_COLUMN_KEY)

用Java习惯了,解析数据喜欢用Bean

class _Location(object):
 def __init__(self):
  self.file = ''
  self.line = 0
  self.column = 0

class _LintBean(object):
 def __init__(self):
  self.id = ''
  self.severity = ''
  self.message = ''
  self.location = _Location()

 def print(self):
  print('find a %s, cause: %s. filePath: %s. line: %s' % (
   self.id, self.message, self.location.file, self.location.line))

处理无用资源

解析完数据,可以得到三种资源:

  • Drawable,就一个文件,可以直接删
  • xml中的一个节点,但是这个xml中就这一个节点,直接删文件
  • xml中的一个节点,这个xml中有多个节点,删除节点

对这三种资源进行区分和删除

for lint in lint_result:
 total_unused_resource += 1
 if lint.id != 'UnusedResources':
  continue
 if lint.location.line != '':
  is_single = _is_single_node(lint.location.file)
  if is_single:
   total_del_file += 1
   del_file(lint.location.file)
  else:
   total_remove_attr += 1
   node_name = get_node_name(lint.message)
   del_node(lint.location.file, node_name)
 else:
  total_del_file += 1
  del_file(lint.location.file)

删除文件

def del_file(file_path):
 try:
  os.remove(file_path)
  print('remove %s success.' % file_path)
 except FileNotFoundError:
  print('remove %s error.' % file_path)

删除节点:

def del_node(file_path, node_name):
 file = minidom.parse(file_path)
 root = file.documentElement
 nodes = root.childNodes
 for node in nodes:
  if node.nodeType in (node.TEXT_NODE, node.COMMENT_NODE):
   continue
  if node_name == node.getAttribute('name'):
   root.removeChild(node)
   file.writexml(open(file_path, 'w', encoding='UTF-8'), encoding='UTF-8')
   print('remove %s, node_name:%s. success!' % (file_path, node_name))
   return

总结

以上所述是小编给大家介绍的使用python 和 lint 删除项目无用资源的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
python实现同时给多个变量赋值的方法
Apr 30 Python
Python正则替换字符串函数re.sub用法示例
Jan 19 Python
Python自动化开发学习之三级菜单制作
Jul 14 Python
Python打印输出数组中全部元素
Mar 13 Python
Python发送邮件测试报告操作实例详解
Dec 08 Python
在python中以相同顺序shuffle两个list的方法
Dec 13 Python
Python的几种主动结束程序方式
Nov 22 Python
np.newaxis 实现为 numpy.ndarray(多维数组)增加一个轴
Nov 30 Python
python使用SQLAlchemy操作MySQL
Jan 02 Python
pytorch-神经网络拟合曲线实例
Jan 15 Python
在Django中自定义filter并在template中的使用详解
May 19 Python
python实现mask矩阵示例(根据列表所给元素)
Jul 30 Python
python机器学习实战之K均值聚类
Dec 20 #Python
Python绘制3d螺旋曲线图实例代码
Dec 20 #Python
python机器学习实战之最近邻kNN分类器
Dec 20 #Python
python3.6 +tkinter GUI编程 实现界面化的文本处理工具(推荐)
Dec 20 #Python
浅谈Python实现Apriori算法介绍
Dec 20 #Python
利用Python如何生成hash值示例详解
Dec 20 #Python
python 3.6 tkinter+urllib+json实现火车车次信息查询功能
Dec 20 #Python
You might like
PHP 面向对象 final类与final方法
2010/05/05 PHP
fetchAll()与mysql_fetch_array()的区别详解
2013/06/05 PHP
PHP垃圾回收机制引用计数器概念分析
2013/06/24 PHP
8个必备的PHP功能实例代码
2013/10/27 PHP
Parse正式发布开源PHP SDK
2014/08/11 PHP
php商品对比功能代码分享
2015/09/24 PHP
php的闭包(Closure)匿名函数初探
2016/02/14 PHP
PHP中abstract(抽象)、final(最终)和static(静态)原理与用法详解
2020/06/05 PHP
PHP终止脚本运行三种实现方法详解
2020/09/01 PHP
新浪的图片新闻效果
2007/01/13 Javascript
jQuery实用基础超详细介绍
2013/04/11 Javascript
js单向链表的具体实现实例
2013/06/21 Javascript
纯JS实现动态时间显示代码
2014/02/08 Javascript
基于编写jQuery的无缝滚动插件
2014/08/02 Javascript
node.js中的fs.futimesSync方法使用说明
2014/12/17 Javascript
javascript实现数独解法
2015/03/14 Javascript
jQuery超酷平面式时钟效果代码分享
2020/03/30 Javascript
jQuery实现Select左右复制移动内容
2016/08/05 Javascript
JQuery实现文字无缝滚动效果示例代码(Marquee插件)
2017/03/07 Javascript
详解Angular Reactive Form 表单验证
2017/07/06 Javascript
Node.JS使用Sequelize操作MySQL的示例代码
2017/10/09 Javascript
用Cordova打包Vue项目的方法步骤
2019/02/02 Javascript
简单了解Vue + ElementUI后台管理模板
2020/04/07 Javascript
详解webpack的clean-webpack-plugin插件报错
2020/10/16 Javascript
Nuxt的路由配置和参数传递方式
2020/11/06 Javascript
[00:13]天涯墨客二技能展示
2018/08/25 DOTA
python实现用户答题功能
2018/01/17 Python
使用Python编写Prometheus监控的方法
2018/10/15 Python
Pytorch提取模型特征向量保存至csv的例子
2020/01/03 Python
Python通过文本和图片生成词云图
2020/05/21 Python
使用Python实现微信拍一拍功能的思路代码
2020/07/09 Python
前端canvas水印快速制作(附完整代码)
2019/09/19 HTML / CSS
抽象类和接口的区别
2012/09/19 面试题
财务人员廉洁自律心得体会
2016/01/13 职场文书
导游词之开封禹王台风景区
2019/12/02 职场文书
Python if else条件语句形式详解
2022/03/24 Python