1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/user/local/bin/python3
#将本文件放在Flutter项目的根目录

from genericpath import isdir
import imghdr
from operator import delitem
import os
from re import search
import re
import string
from sys import path
import sys
from tokenize import String
from typing import List

print("---Analyze unused Assets----")
# 配置项目路径 -- 项目目录
projectAbsRootPath = "/Users/liuliang/workplace/2023/chat_ai"
# 图片所在的资源目录路径
assetPath="/images"
#项目中dart代码所在目录
libPath = projectAbsRootPath+ "/lib"
assetAbPath = projectAbsRootPath+assetPath

print("projectRootPath:" + projectAbsRootPath + " assets:" +assetAbPath + " lib:" + libPath)
print("----------开始查找图片--------------")
#遍历目录,将图片存储到list中的方法
def searchImage(filePath:String):
list = []
isDir = os.path.isdir(filePath)
if isDir:
for f in os.listdir(filePath):
if f.startswith("."):
print(filePath+"/"+f)
else:
tList = searchImage(filePath+"/"+f)
list.extend(tList)
else:
if imghdr.what(filePath) in {"jpg","bmp","jpeg","rgb","tif","png"}:
list.append(filePath)
return list

#项目中使用的图片资源路径集合
imageList = searchImage(assetAbPath)

print("-------------遍历dart文件,分析未使用的图片---------")
def matchAndDelImage(contentStr:String,list:List):
#遍历拷贝的list,操作原始的list,list[:]是对原始的一个拷贝
for imgPath in list[:]:
#以文件名匹配图片的使用
# pList = imgPath.split("/")
# imgName = pList[-1]
#以使用的文件路径匹配图片
index = imgPath.find(assetPath)
imgName = imgPath[index+1:]

match = re.search(imgName,contentStr)
if match:
list.remove(imgPath)
# print("used-->" + imgPath)

#
def searchImageInDart(filePath:String,list:List):
if os.path.isdir(filePath):
for f in os.listdir(filePath):
searchImageInDart(filePath+"/"+f,list)
else:
with open(filePath,"r") as f:
contentStr = f.read()
f.close()
if len(contentStr) != 0:
matchAndDelImage(contentStr,list)

#
searchImageInDart(libPath,imageList)

print("------在dart文件中未找到被使用的图片如下-----size:" + str(len(imageList)))
for img in imageList:
print("may be unused-->" + img)
os.remove(img)
print("-------------------分析完成-------------------------------")