builder.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. # -*- coding:utf-8 -*-
  2. import time
  3. import sys
  4. import os
  5. import json
  6. import subprocess
  7. '''
  8. 配置全局变量
  9. '''
  10. JSONFILE = None
  11. SHELLFILE = None
  12. print(sys.argv[0]) # sys.argv[0] 类似于shell中的$0,但不是脚本名称,而是脚本的路径
  13. if len(sys.argv) == 2:
  14. JSONFILE = sys.argv[1] # 表示Json参数文件路径;
  15. if len(sys.argv) == 3:
  16. SHELLFILE = sys.argv[2] # 表示Shell脚本文件路径;
  17. # 输入开始时间;
  18. print("Start",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
  19. # 源码路径
  20. CODE_DIR = None
  21. # 脚本名称;
  22. SCRIPT_NAME = None
  23. # 编译前的参数
  24. PREV_ARG = None
  25. # 脚本参数
  26. SCRIPT_ARG = None
  27. # 编译后的参数
  28. AFTER_ARG = None
  29. # 源码目录名称;
  30. CODE_FOLDER_NAME = None
  31. # 解析json文件;
  32. def loadJson():
  33. global CODE_DIR
  34. global PREV_ARG
  35. global JSONFILE
  36. global SCRIPT_ARG
  37. global AFTER_ARG
  38. global SCRIPT_NAME
  39. global CODE_FOLDER_NAME
  40. print(u"loadJson")
  41. if JSONFILE is None or JSONFILE.__len__() == 0:
  42. print(u"use default josn arg")
  43. JSONFILE=sys.path[0]+"/arg.json"
  44. #JSONFILE = "arg.json"
  45. if os.path.exists(JSONFILE) is False:
  46. print(u"json file doesn't exist")
  47. return False
  48. try:
  49. data = open(JSONFILE, 'r')
  50. args = json.load(data)
  51. except Exception as e:
  52. print("An error occurred:"+e)
  53. return False
  54. print(args['pre-compile'])
  55. print(args['after-compile'])
  56. print(args['compile'])
  57. CODE_DIR = args['code-dir']
  58. CODE_FOLDER_NAME = CODE_DIR.split('/')[-1]
  59. SCRIPT_NAME = args['compile-script']
  60. PREV_ARG = args['pre-compile']
  61. SCRIPT_ARG = args['compile']
  62. AFTER_ARG = args['after-compile']
  63. return True
  64. # 不使用重定向;
  65. def cmdExecute_NoRidrect(cmd, dir=None):
  66. print(str.format("cmd start:%s, %s") % (cmd, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
  67. proc = subprocess.Popen(cmd, shell=True, cwd=dir)
  68. # 等待完成;
  69. proc.wait()
  70. print(str.format("cmd end:%s, %s") % (cmd, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
  71. # 重定向标准输出、标准错误;
  72. def cmdExecute_Ridrect(cmd, dir=None):
  73. print(str.format("cmd start:%s, %s") % (cmd, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
  74. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=dir)
  75. # 等待完成;
  76. stdout,stderr = proc.communicate()
  77. if proc.returncode == 0:
  78. print(u'cmd finished')
  79. # 返回执行结果;
  80. print("stdout=",stdout)
  81. print("stderr=",stderr)
  82. print(str.format("cmd end:%s, %s") % (cmd, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
  83. return stdout
  84. def prev_compile():
  85. global PREV_ARG
  86. global CODE_DIR
  87. print("prev_compile", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
  88. if PREV_ARG is None or PREV_ARG.__len__() == 0:
  89. print("prev args is empty")
  90. return False
  91. # Python无法将字符串'false'转为布尔类型;
  92. if 'clean' in PREV_ARG:
  93. if type(PREV_ARG['clean']) == type(u'str'):
  94. PREV_ARG['clean'] = True if PREV_ARG['clean'].lower() == u'true' else False
  95. print(type(PREV_ARG['clean']), PREV_ARG['clean'])
  96. if 'sync' in PREV_ARG:
  97. if type(PREV_ARG['sync']) == type(u'str'):
  98. PREV_ARG['sync'] = True if PREV_ARG['sync'].lower() == u'true' else False
  99. print(type(PREV_ARG['sync']), PREV_ARG['sync'])
  100. if 'redownload' in PREV_ARG:
  101. if type(PREV_ARG['redownload']) == type(u'str'):
  102. PREV_ARG['redownload'] = True if PREV_ARG['redownload'].lower() == u'true' else False
  103. print(type(PREV_ARG['redownload']), PREV_ARG['redownload'])
  104. # 更新代码;
  105. commands=[]
  106. commands.append(str.format("cd %s") % CODE_DIR)
  107. commands.append("rm -rf Target")
  108. # Java创建会话终端(导入了所有环境变量),无须再export,解决repo:commnand not found的问题;
  109. #commands.append("export PATH=$(echo $PATH)")
  110. if 'clean' in PREV_ARG and PREV_ARG['clean']:
  111. print("enable clean")
  112. commands.append("repo forall -c \"pwd &&git clean -xfd && git checkout .\"")
  113. # 更新代码;
  114. if 'sync' in PREV_ARG and PREV_ARG['sync']:
  115. print("enable sync")
  116. commands.append("repo sync")
  117. # 重新下载;
  118. if 'redownload' in PREV_ARG and PREV_ARG['redownload']:
  119. print("enable redownload")
  120. commands.append(str.format("rm -rf !(%s|%s|%s|%s)") % ("builder.py", "arg.json", SCRIPT_NAME, "ftp.py"))
  121. commands.append(str.format("repo init -u %s") % (PREV_ARG['branch-addr']))
  122. commands.append("repo sync")
  123. # 执行所有命令;
  124. commandline=';'.join(commands)
  125. cmdExecute_Ridrect(commandline)
  126. def call_script():
  127. global SCRIPT_ARG
  128. print("call_script", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
  129. if SCRIPT_ARG is None or SCRIPT_ARG.__len__() == 0:
  130. print("script args is empty")
  131. return False
  132. # 生成命令行参数;
  133. commandline = ''
  134. for item in SCRIPT_ARG:
  135. line = str.format("%s=%s ") % (item, SCRIPT_ARG[item])
  136. commandline = commandline + line
  137. print("script args is:"+commandline)
  138. if commandline.__len__() == 0 or commandline.index("=") == -1:
  139. print("commandline is empty or format error!")
  140. return False
  141. print("start to compile")
  142. # 调用编译脚本时,不需要重定向,否则无法生成日志;
  143. cmdExecute_NoRidrect(str.format("cd %s;chmod 777 %s;./%s %s")%(CODE_DIR,SCRIPT_NAME,SCRIPT_NAME,commandline), CODE_DIR)
  144. return True
  145. def after_compile():
  146. global AFTER_ARG
  147. print("after_compile", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
  148. if AFTER_ARG is None or AFTER_ARG.__len__() == 0:
  149. print("after args is empty")
  150. return False
  151. if 'Scp2OtherServer' in AFTER_ARG:
  152. if type(AFTER_ARG['Scp2OtherServer']) == type(u'str'):
  153. AFTER_ARG['Scp2OtherServer'] = True if AFTER_ARG['Scp2OtherServer'].lower() == u'true' else False
  154. print(type(AFTER_ARG['Scp2OtherServer']), AFTER_ARG['Scp2OtherServer'])
  155. # 上传到其他服务器;
  156. if 'Scp2OtherServer' in AFTER_ARG and AFTER_ARG['Scp2OtherServer']:
  157. commands=[]
  158. commands.append(str.format("cd %s/Target/") % CODE_DIR)
  159. commands.append("cd $(ls|grep V8)")
  160. commands.append("pwd")
  161. commands.append("ls")
  162. # 创建目录;
  163. ScpDir=AFTER_ARG['ScpServerPath']+time.strftime("%Y%m%d%H%M%S")
  164. commands.append(str.format('ssh %s@%s "[ -d %s ] && echo ok || mkdir -p %s"') % (AFTER_ARG['ScpUserName'], AFTER_ARG['ScpServerName'], ScpDir, ScpDir))
  165. commands.append(str.format("scp -r OTA %s@%s:%s") % (AFTER_ARG['ScpUserName'], AFTER_ARG['ScpServerName'], ScpDir))
  166. commands.append(str.format("scp -r Reports/* %s@%s:%s") % (AFTER_ARG['ScpUserName'], AFTER_ARG['ScpServerName'], ScpDir))
  167. commands.append(str.format("scp -r USB/* %s@%s:%s") % (AFTER_ARG['ScpUserName'], AFTER_ARG['ScpServerName'], ScpDir))
  168. # 执行所有命令;
  169. commandline=';'.join(commands)
  170. cmdExecute_Ridrect(commandline)
  171. if __name__ == "__main__":
  172. # os.system('cd ~/2851M; ls -al; repo sync') # 可用命令格式;
  173. # subprocess.call('cd ~;ls -al;cd ~/2851M; ls -al; repo sync', shell=True)
  174. # subprocess.call(["cd ~", "ls -al","cd ~/2851M", "ls -al", "repo sync"], shell=False) 错误的执行方式;
  175. ret = loadJson()
  176. if ret is True:
  177. prev_compile()
  178. call_script()
  179. after_compile()
  180. else:
  181. print(u"doesn't build")