file_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. import os
  2. import os.path
  3. import shutil
  4. import subprocess
  5. import platform
  6. import sys
  7. import hashlib
  8. def getFullToolPath(name):
  9. '''
  10. 获取工具的目录
  11. '''
  12. return getFullPath('tools', name)
  13. def getFullGameApk(name):
  14. '''
  15. 获取游戏的原始包
  16. '''
  17. return getFullPath('game', name, name + '.apk')
  18. def getFullSDKPath(sdk):
  19. '''
  20. 获取sdk的目录
  21. '''
  22. return getFullPath('sdk', sdk)
  23. def getFullLogSDKPath(sdk):
  24. '''
  25. 获取logsdk的目录
  26. '''
  27. return getFullPath('log_sdk', sdk)
  28. def getDecompliePath(game, sdk, subChannel, cache):
  29. '''
  30. 获取解包的目录
  31. '''
  32. return getFullPath('gen', game, sdk, subChannel, cache)
  33. def getSubChannelPath(game, sdk, subChannel):
  34. '''
  35. 获取子渠道的目录
  36. '''
  37. return getFullPath('game', game, sdk, subChannel)
  38. def getChannelPath(game, sdk):
  39. '''
  40. 获取渠道的目录
  41. '''
  42. return getFullPath('game', game, sdk)
  43. def getFullGamePath(game):
  44. '''
  45. 获取游戏的目录
  46. '''
  47. return getFullPath('game', game)
  48. def getFullInternalPath():
  49. '''
  50. 获取内部目录
  51. '''
  52. return os.path.join(getCurrentPath(), 'internal')
  53. def getFullPath(type, *name):
  54. path = os.path.join(getCurrentPath(), type)
  55. for n in name:
  56. path = os.path.join(path, str(n))
  57. return path
  58. def getCurrentPath():
  59. '''
  60. 当前目录
  61. '''
  62. return sys.path[0]
  63. def execFormatCmd(cmd, cd = None):
  64. '''
  65. 执行cmd命令
  66. 返回值:None —— 子进程尚未结束;
  67. ==0 —— 子进程正常退出;
  68. > 0—— 子进程异常退出,returncode对应于出错码;
  69. < 0—— 子进程被信号杀掉了。
  70. '''
  71. '''print(cmd)
  72. p = os.popen(cmd)
  73. print(p.read())'''
  74. ret = 0
  75. try:
  76. s = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=cd)
  77. stdoutput, erroutput = s.communicate()
  78. if platform.system() == 'Windows':
  79. stdoutput = stdoutput.decode('gbk')
  80. erroutput = erroutput.decode('gbk')
  81. '''
  82. None —— 子进程尚未结束;
  83. ==0 —— 子进程正常退出;
  84. > 0—— 子进程异常退出,returncode对应于出错码;
  85. < 0—— 子进程被信号杀掉了。
  86. '''
  87. ret = s.returncode
  88. if ret:
  89. print('*******ERROR*******')
  90. print(stdoutput)
  91. print(erroutput)
  92. print('*******************')
  93. cmd = 'error::' + cmd + ' !!!exec Fail!!! '
  94. else:
  95. print(stdoutput)
  96. print(erroutput)
  97. cmd = cmd + ' !!!exec success!!! '
  98. print(cmd)
  99. except Exception as e:
  100. print('Exception ' + e)
  101. return 1
  102. return ret
  103. def execJarCmd(jar, params):
  104. '''
  105. 执行jar
  106. '''
  107. return execFormatCmd('java -jar "%s" %s' % (jar, params))
  108. def copyFileAllDir(fromDir, toDir, delete = False, support = None):
  109. '''
  110. 拷贝目录下所有文件文件
  111. '''
  112. #print('copy all file %s --> %s' % (fromDir, toDir))
  113. ret = copyDir(fromDir, toDir, delete, support)
  114. if ret:
  115. return ret
  116. if delete:
  117. deleteFolder(fromDir)
  118. return 0
  119. def copyDir(fromDir, toDir, delete = False, support = None):
  120. '''
  121. 拷贝目录下所有文件文件
  122. '''
  123. #print('copy all file %s --> %s' % (fromDir, toDir))
  124. if not os.path.exists(fromDir):
  125. print('%s not exists!' % fromDir)
  126. return 1
  127. if not os.path.isdir(fromDir):
  128. print('%s not a dir!' % fromDir)
  129. return 1
  130. for fromFile in os.listdir(fromDir):
  131. fromFilePath = os.path.join(fromDir, fromFile)
  132. toFilePath = os.path.join(toDir, fromFile)
  133. if os.path.isdir(fromFilePath):
  134. # 不支持的类型
  135. if support is not None and fromFile not in support:
  136. continue
  137. ret = copyDir(fromFilePath, toFilePath, delete, support)
  138. if ret:
  139. return ret
  140. else:
  141. ret = copyFile(fromFilePath, toFilePath, delete)
  142. if ret:
  143. return ret
  144. return 0
  145. def copyFile(formFile, toFile, delete = False):
  146. '''
  147. 拷贝文件
  148. '''
  149. if not os.path.isfile(formFile):
  150. print('%s not a file!' % formFile)
  151. return 1
  152. fpath, fname = os.path.split(toFile) #分离文件名和路径
  153. if not os.path.exists(fpath):
  154. print('%s not exists, crate' % fpath)
  155. os.makedirs(fpath) #创建路径
  156. '''if os.path.exists(toFile) and os.path.getsize(formFile) > 104857600 and equalsFile(formFile, toFile):
  157. print('skip copy %s --> %s' % (formFile, toFile))
  158. if delete:
  159. os.remove(formFile)
  160. print('remove %s' % formFile)
  161. return 0'''
  162. if delete:
  163. shutil.move(formFile, toFile) #移动文件
  164. print('move %s --> %s' % (formFile, toFile))
  165. else:
  166. shutil.copyfile(formFile, toFile) #复制文件
  167. print('copy %s --> %s' % (formFile, toFile))
  168. return 0
  169. def replaceContent(file, oldText, newText):
  170. '''
  171. 全局替换
  172. '''
  173. with openFile(file, 'r+') as f:
  174. t = f.read()
  175. t = t.replace(oldText, newText)
  176. #读写偏移位置移到最开始处
  177. f.seek(0, 0)
  178. #清空内容
  179. f.truncate()
  180. f.write(t)
  181. def readFile(file):
  182. '''
  183. 读取文件内容
  184. '''
  185. content = ''
  186. with openFile(file, 'r') as f:
  187. content = f.read()
  188. return content
  189. def createFile(file, content):
  190. '''
  191. 创建文件
  192. '''
  193. fpath, fname = os.path.split(file) #分离文件名和路径
  194. if not os.path.exists(fpath):
  195. os.makedirs(fpath)
  196. with openFile(file, 'w') as f:
  197. f.write(content)
  198. f.close()
  199. def openFile(file, mode):
  200. return open(file, mode, encoding='UTF-8')
  201. def deleteFolder(folder):
  202. '''
  203. 删除目录以及目录下的文件
  204. '''
  205. if not os.path.exists(folder):
  206. return
  207. print('remove %s ...' % folder)
  208. shutil.rmtree(folder)
  209. print('removed %s' % folder)
  210. def getAAPTPath():
  211. '''
  212. 获取aapt
  213. '''
  214. return getToolWithSystem('aapt')
  215. def getAAPT2Path():
  216. '''
  217. 获取aapt2
  218. '''
  219. return getToolWithSystem('aapt2')
  220. def getAndroidCompileToolPath():
  221. '''
  222. 获取android.jar
  223. '''
  224. return getFullToolPath('android.jar')
  225. def getDxPath():
  226. '''
  227. 获取dx.jar
  228. '''
  229. return getFullToolPath('dx.jar')
  230. def getD8Path():
  231. '''
  232. 获取d8.jar
  233. '''
  234. return getFullToolPath('d8.jar')
  235. def getAlignPath():
  236. '''
  237. 获取zipalign
  238. '''
  239. return getToolWithSystem('zipalign')
  240. def getMultiDexPath():
  241. '''
  242. 获取multidex.jar
  243. '''
  244. return getFullToolPath('android-support-multidex.jar')
  245. def getApkToolPath():
  246. '''
  247. 获取apktool.jar
  248. '''
  249. return getFullToolPath('apktool_2.4.0.jar')
  250. def getBaksmaliPath():
  251. '''
  252. 获取baksmali.jar
  253. '''
  254. return getFullToolPath('baksmali-2.3.jar')
  255. def getApksignerPath():
  256. '''
  257. 获取apksigner.jar
  258. '''
  259. return getFullToolPath('apksigner.jar')
  260. def getWallePath():
  261. '''
  262. 获取walle-cli-all.jar
  263. '''
  264. return getFullToolPath('walle-cli-all.jar')
  265. def getOutApkPath(game, sdk, subChannel, cache):
  266. '''
  267. 获取输出的apk的目录
  268. '''
  269. return getFullPath('target', game, sdk, cache, '%s_%s_%s.apk' % (game, sdk, subChannel))
  270. def getAlignApkPath(game, sdk, subChannel, cache):
  271. '''
  272. 获取输出的apk的目录
  273. '''
  274. return getFullPath('target', game, sdk, cache, '%s_%s_%s_align.apk' % (game, sdk, subChannel))
  275. def getRenameApkPath(game, sdk, cache, name):
  276. '''
  277. 重命名输出的apk名称
  278. '''
  279. return getFullPath('target', game, sdk, cache, '%s.apk' % name)
  280. def getSignApkPath(game, sdk, subChannel, cache):
  281. '''
  282. 获取输出的apk的目录
  283. '''
  284. return getFullPath('target', game, sdk, cache, '%s_%s_%s_signed.apk' % (game, sdk, subChannel))
  285. def getPackagePath(basePath, packageName):
  286. '''
  287. 包名对应的目录
  288. '''
  289. packageNameSplit = packageName.split('.')
  290. newPath = basePath
  291. for item in packageNameSplit:
  292. newPath = os.path.join(newPath, item)
  293. return newPath
  294. def getToolWithSystem(tool):
  295. '''
  296. 获取系统相关工具
  297. '''
  298. system = getSystemPath()
  299. suffix = getSystemSuffix()
  300. return os.path.join(getFullToolPath(system), tool + suffix)
  301. def getSystemPath():
  302. '''
  303. 获取系统目录
  304. '''
  305. if platform.system() == 'Windows':
  306. return 'win'
  307. else:
  308. return 'linux'
  309. def getSystemSuffix():
  310. '''
  311. 系统工具后缀
  312. '''
  313. if platform.system() == 'Windows':
  314. return '.exe'
  315. else:
  316. return ''
  317. def getApplicationSmaliIndex(file):
  318. '''
  319. 获取application.smali的MultiDex信息
  320. '''
  321. content = ('invoke-super', '->attachBaseContext(Landroid/content/Context;)V')
  322. index = -1
  323. with openFile(file, 'r') as f:
  324. line = f.readline()
  325. while line:
  326. if content[0] in line and content[1] in line:
  327. index = f.tell()
  328. break
  329. line = f.readline()
  330. return index
  331. def insertApplicationSmali(file, index):
  332. '''
  333. 获取application.smali插入MultiDex的信息
  334. '''
  335. if index == -1:
  336. # append
  337. content = '''# virtual methods
  338. .method protected attachBaseContext(Landroid/content/Context;)V
  339. .locals 0
  340. .param p1, "context" # Landroid/content/Context;
  341. invoke-super {p0, p1}, Landroid/app/Application;->attachBaseContext(Landroid/content/Context;)V
  342. invoke-static {p0}, Landroid/support/multidex/MultiDex;->install(Landroid/content/Context;)V
  343. return-void
  344. .end method'''
  345. with openFile(file, 'a') as f:
  346. f.write(content)
  347. else:
  348. # insert
  349. content = '\n\tinvoke-static {p0}, Landroid/support/multidex/MultiDex;->install(Landroid/content/Context;)V\n'
  350. with openFile(file, 'r+') as f:
  351. f.seek(index)
  352. last = f.read()
  353. f.seek(index)
  354. f.write(content)
  355. f.write(last)
  356. return 0
  357. def changeVersion(yml, versionCode = None, versionName = None, targetSdkVersion = None):
  358. if versionCode is None and versionName is None and targetSdkVersion is None:
  359. return 0
  360. tag = ['versionCode:', 'versionName:', 'targetSdkVersion:']
  361. with openFile(yml, 'r+') as f:
  362. content = ''
  363. line = f.readline()
  364. while line:
  365. if versionCode is not None and tag[0] in line:
  366. content += ' versionCode: \'%s\'\n' % versionCode
  367. elif versionName is not None and tag[1] in line:
  368. content += ' versionName: %s\n' % versionName
  369. elif targetSdkVersion is not None and tag[2] in line:
  370. content += ' targetSdkVersion: \'%s\'\n' % targetSdkVersion
  371. else:
  372. content += line
  373. line = f.readline()
  374. f.seek(0, 0)
  375. f.truncate()
  376. f.write(content)
  377. return 0
  378. def changeMinSdkVersion(yml, minSdkVersion):
  379. with openFile(yml, 'r+') as f:
  380. content = ''
  381. line = f.readline()
  382. while line:
  383. if 'minSdkVersion' in line:
  384. start = line.index("'")
  385. version = int(line[start+1:-2])
  386. if version < minSdkVersion:
  387. content += ' minSdkVersion: \'%s\'\n' % minSdkVersion
  388. else:
  389. return 0
  390. else:
  391. content += line
  392. line = f.readline()
  393. f.seek(0, 0)
  394. f.truncate()
  395. f.write(content)
  396. return 0
  397. def list_files(src, resFiles):
  398. '''
  399. 列出目录下所有的文件
  400. '''
  401. if os.path.exists(src):
  402. if os.path.isfile(src):
  403. resFiles.append(src)
  404. elif os.path.isdir(src):
  405. for f in os.listdir(src):
  406. list_files(os.path.join(src, f), resFiles)
  407. return resFiles
  408. def getFileMd5(f):
  409. '''
  410. 获取文件的md5
  411. '''
  412. m = hashlib.md5()
  413. while True:
  414. data = f.read(1024) #将文件分块读取
  415. if not data:
  416. break
  417. m.update(data)
  418. return m.hexdigest()
  419. def equalsFile(file1, file2):
  420. '''
  421. 比较两个文件是否是同一个文件
  422. '''
  423. with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
  424. file1Md5 = getFileMd5(f1)
  425. file2Md5 = getFileMd5(f2)
  426. #print('file1Md5:',file1Md5)
  427. #print('file2Md5:',file2Md5)
  428. return file1Md5 == file2Md5
  429. def getExecPermission(file):
  430. '''
  431. linux下获取执行权限
  432. '''
  433. if platform.system() == 'Windows':
  434. return 0
  435. return execFormatCmd('chmod +x "%s"' % file)