file_utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. elif platform.system() == 'Darwin':
  308. print ('---------macos----------')
  309. return 'macos'
  310. else:
  311. return 'linux'
  312. def getSystemSuffix():
  313. '''
  314. 系统工具后缀
  315. '''
  316. if platform.system() == 'Windows':
  317. return '.exe'
  318. else:
  319. return ''
  320. def getApplicationSmaliIndex(file):
  321. '''
  322. 获取application.smali的MultiDex信息
  323. '''
  324. content = ('invoke-super', '->attachBaseContext(Landroid/content/Context;)V')
  325. index = -1
  326. with openFile(file, 'r') as f:
  327. line = f.readline()
  328. while line:
  329. if content[0] in line and content[1] in line:
  330. index = f.tell()
  331. break
  332. line = f.readline()
  333. return index
  334. def insertApplicationSmali(file, index):
  335. '''
  336. 获取application.smali插入MultiDex的信息
  337. '''
  338. if index == -1:
  339. # append
  340. content = '''# virtual methods
  341. .method protected attachBaseContext(Landroid/content/Context;)V
  342. .locals 0
  343. .param p1, "context" # Landroid/content/Context;
  344. invoke-super {p0, p1}, Landroid/app/Application;->attachBaseContext(Landroid/content/Context;)V
  345. invoke-static {p0}, Landroid/support/multidex/MultiDex;->install(Landroid/content/Context;)V
  346. return-void
  347. .end method'''
  348. with openFile(file, 'a') as f:
  349. f.write(content)
  350. else:
  351. # insert
  352. content = '\n\tinvoke-static {p0}, Landroid/support/multidex/MultiDex;->install(Landroid/content/Context;)V\n'
  353. with openFile(file, 'r+') as f:
  354. f.seek(index)
  355. last = f.read()
  356. f.seek(index)
  357. f.write(content)
  358. f.write(last)
  359. return 0
  360. def changeVersion(yml, versionCode = None, versionName = None, targetSdkVersion = None):
  361. if versionCode is None and versionName is None and targetSdkVersion is None:
  362. return 0
  363. tag = ['versionCode:', 'versionName:', 'targetSdkVersion:']
  364. with openFile(yml, 'r+') as f:
  365. content = ''
  366. line = f.readline()
  367. while line:
  368. if versionCode is not None and tag[0] in line:
  369. content += ' versionCode: \'%s\'\n' % versionCode
  370. elif versionName is not None and tag[1] in line:
  371. content += ' versionName: %s\n' % versionName
  372. elif targetSdkVersion is not None and tag[2] in line:
  373. content += ' targetSdkVersion: \'%s\'\n' % targetSdkVersion
  374. else:
  375. content += line
  376. line = f.readline()
  377. f.seek(0, 0)
  378. f.truncate()
  379. f.write(content)
  380. return 0
  381. def changeMinSdkVersion(yml, minSdkVersion):
  382. with openFile(yml, 'r+') as f:
  383. content = ''
  384. line = f.readline()
  385. while line:
  386. if 'minSdkVersion' in line:
  387. start = line.index("'")
  388. version = int(line[start+1:-2])
  389. if version < minSdkVersion:
  390. content += ' minSdkVersion: \'%s\'\n' % minSdkVersion
  391. else:
  392. return 0
  393. else:
  394. content += line
  395. line = f.readline()
  396. f.seek(0, 0)
  397. f.truncate()
  398. f.write(content)
  399. return 0
  400. def list_files(src, resFiles):
  401. '''
  402. 列出目录下所有的文件
  403. '''
  404. if os.path.exists(src):
  405. if os.path.isfile(src):
  406. resFiles.append(src)
  407. elif os.path.isdir(src):
  408. for f in os.listdir(src):
  409. list_files(os.path.join(src, f), resFiles)
  410. return resFiles
  411. def getFileMd5(f):
  412. '''
  413. 获取文件的md5
  414. '''
  415. m = hashlib.md5()
  416. while True:
  417. data = f.read(1024) #将文件分块读取
  418. if not data:
  419. break
  420. m.update(data)
  421. return m.hexdigest()
  422. def equalsFile(file1, file2):
  423. '''
  424. 比较两个文件是否是同一个文件
  425. '''
  426. with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
  427. file1Md5 = getFileMd5(f1)
  428. file2Md5 = getFileMd5(f2)
  429. #print('file1Md5:',file1Md5)
  430. #print('file2Md5:',file2Md5)
  431. return file1Md5 == file2Md5
  432. def getExecPermission(file):
  433. '''
  434. linux下获取执行权限
  435. '''
  436. if platform.system() == 'Windows':
  437. return 0
  438. return execFormatCmd('chmod +x "%s"' % file)