file_utils.py 13 KB

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