file_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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):
  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)
  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 getAndroidCompileToolPath():
  216. '''
  217. 获取android.jar
  218. '''
  219. return getFullToolPath('android.jar')
  220. def getDxPath():
  221. '''
  222. 获取dx.jar
  223. '''
  224. return getFullToolPath('dx.jar')
  225. def getAlignPath():
  226. '''
  227. 获取zipalign
  228. '''
  229. return getToolWithSystem('zipalign')
  230. def getMultiDexPath():
  231. '''
  232. 获取multidex.jar
  233. '''
  234. return getFullToolPath('android-support-multidex.jar')
  235. def getApkToolPath():
  236. '''
  237. 获取apktool.jar
  238. '''
  239. return getFullToolPath('apktool_2.3.4.jar')
  240. def getBaksmaliPath():
  241. '''
  242. 获取baksmali.jar
  243. '''
  244. return getFullToolPath('baksmali-2.1.3.jar')
  245. def getApksignerPath():
  246. '''
  247. 获取apksigner.jar
  248. '''
  249. return getFullToolPath('apksigner.jar')
  250. def getWallePath():
  251. '''
  252. 获取walle-cli-all.jar
  253. '''
  254. return getFullToolPath('walle-cli-all.jar')
  255. def getOutApkPath(game, sdk, subChannel, cache):
  256. '''
  257. 获取输出的apk的目录
  258. '''
  259. return getFullPath('target', game, sdk, cache, '%s_%s_%s.apk' % (game, sdk, subChannel))
  260. def getAlignApkPath(game, sdk, subChannel, cache):
  261. '''
  262. 获取输出的apk的目录
  263. '''
  264. return getFullPath('target', game, sdk, cache, '%s_%s_%s_align.apk' % (game, sdk, subChannel))
  265. def getRenameApkPath(game, sdk, cache, name):
  266. '''
  267. 重命名输出的apk名称
  268. '''
  269. return getFullPath('target', game, sdk, cache, '%s.apk' % name)
  270. def getSignApkPath(game, sdk, subChannel, cache):
  271. '''
  272. 获取输出的apk的目录
  273. '''
  274. return getFullPath('target', game, sdk, cache, '%s_%s_%s_signed.apk' % (game, sdk, subChannel))
  275. def getPackagePath(basePath, packageName):
  276. '''
  277. 包名对应的目录
  278. '''
  279. packageNameSplit = packageName.split('.')
  280. newPath = basePath
  281. for item in packageNameSplit:
  282. newPath = os.path.join(newPath, item)
  283. return newPath
  284. def getToolWithSystem(tool):
  285. '''
  286. 获取系统相关工具
  287. '''
  288. system = getSystemPath()
  289. suffix = getSystemSuffix()
  290. return os.path.join(getFullToolPath(system), tool + suffix)
  291. def getSystemPath():
  292. '''
  293. 获取系统目录
  294. '''
  295. if platform.system() == 'Windows':
  296. return 'win'
  297. else:
  298. return 'linux'
  299. def getSystemSuffix():
  300. '''
  301. 系统工具后缀
  302. '''
  303. if platform.system() == 'Windows':
  304. return '.exe'
  305. else:
  306. return ''
  307. def getApplicationSmaliIndex(file):
  308. '''
  309. 获取application.smali的MultiDex信息
  310. '''
  311. content = ('invoke-super', '->attachBaseContext(Landroid/content/Context;)V')
  312. index = -1
  313. with openFile(file, 'r') as f:
  314. line = f.readline()
  315. while line:
  316. if content[0] in line and content[1] in line:
  317. index = f.tell()
  318. break
  319. line = f.readline()
  320. return index
  321. def insertApplicationSmali(file, index):
  322. '''
  323. 获取application.smali插入MultiDex的信息
  324. '''
  325. if index == -1:
  326. # append
  327. content = '''# virtual methods
  328. .method protected attachBaseContext(Landroid/content/Context;)V
  329. .locals 0
  330. .param p1, "context" # Landroid/content/Context;
  331. invoke-super {p0, p1}, Landroid/app/Application;->attachBaseContext(Landroid/content/Context;)V
  332. invoke-static {p0}, Landroid/support/multidex/MultiDex;->install(Landroid/content/Context;)V
  333. return-void
  334. .end method'''
  335. with openFile(file, 'a') as f:
  336. f.write(content)
  337. else:
  338. # insert
  339. content = '\n\tinvoke-static {p0}, Landroid/support/multidex/MultiDex;->install(Landroid/content/Context;)V\n'
  340. with openFile(file, 'r+') as f:
  341. f.seek(index)
  342. last = f.read()
  343. f.seek(index)
  344. f.write(content)
  345. f.write(last)
  346. return 0
  347. def changeVersion(yml, versionCode = None, versionName = None, targetSdkVersion = None):
  348. if versionCode is None and versionName is None and targetSdkVersion is None:
  349. return 0
  350. tag = ['versionCode:', 'versionName:', 'targetSdkVersion:']
  351. with openFile(yml, 'r+') as f:
  352. content = ''
  353. line = f.readline()
  354. while line:
  355. if versionCode is not None and tag[0] in line:
  356. content += ' versionCode: \'%s\'\n' % versionCode
  357. elif versionName is not None and tag[1] in line:
  358. content += ' versionName: %s\n' % versionName
  359. elif targetSdkVersion is not None and tag[2] in line:
  360. content += ' targetSdkVersion: \'%s\'\n' % targetSdkVersion
  361. else:
  362. content += line
  363. line = f.readline()
  364. f.seek(0, 0)
  365. f.truncate()
  366. f.write(content)
  367. return 0
  368. def changeMinSdkVersion(yml, minSdkVersion):
  369. with openFile(yml, 'r+') as f:
  370. content = ''
  371. line = f.readline()
  372. while line:
  373. if 'minSdkVersion' in line:
  374. start = line.index("'")
  375. version = int(line[start+1:-2])
  376. if version < minSdkVersion:
  377. content += ' minSdkVersion: \'%s\'\n' % minSdkVersion
  378. else:
  379. return 0
  380. else:
  381. content += line
  382. line = f.readline()
  383. f.seek(0, 0)
  384. f.truncate()
  385. f.write(content)
  386. return 0
  387. def list_files(src, resFiles):
  388. '''
  389. 列出目录下所有的文件
  390. '''
  391. if os.path.exists(src):
  392. if os.path.isfile(src):
  393. resFiles.append(src)
  394. elif os.path.isdir(src):
  395. for f in os.listdir(src):
  396. list_files(os.path.join(src, f), resFiles)
  397. return resFiles
  398. def getFileMd5(f):
  399. '''
  400. 获取文件的md5
  401. '''
  402. m = hashlib.md5()
  403. while True:
  404. data = f.read(1024) #将文件分块读取
  405. if not data:
  406. break
  407. m.update(data)
  408. return m.hexdigest()
  409. def equalsFile(file1, file2):
  410. '''
  411. 比较两个文件是否是同一个文件
  412. '''
  413. with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
  414. file1Md5 = getFileMd5(f1)
  415. file2Md5 = getFileMd5(f2)
  416. #print('file1Md5:',file1Md5)
  417. #print('file2Md5:',file2Md5)
  418. return file1Md5 == file2Md5
  419. def getExecPermission(file):
  420. '''
  421. linux下获取执行权限
  422. '''
  423. if platform.system() == 'Windows':
  424. return 0
  425. return execFormatCmd('chmod +x "%s"' % file)