vcs_info.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import base64
  2. import json
  3. import os
  4. import re
  5. import sys
  6. import shutil
  7. import tempfile
  8. import textwrap
  9. import zipfile
  10. class _Formatting(object):
  11. @staticmethod
  12. def is_str(strval):
  13. return isinstance(strval, (bytes, str))
  14. @staticmethod
  15. def encoding_needed(strval):
  16. return isinstance(strval, str)
  17. @staticmethod
  18. def escape_special_symbols(strval):
  19. encoding_needed = _Formatting.encoding_needed(strval)
  20. c_str = strval.encode('utf-8') if encoding_needed else strval
  21. retval = b""
  22. for c in c_str:
  23. c = bytes([c])
  24. if c in (b"\\", b"\""):
  25. retval += b"\\" + c
  26. elif ord(c) < ord(' '):
  27. retval += c.decode('latin-1').encode('unicode_escape')
  28. else:
  29. retval += c
  30. return retval.decode('utf-8') if encoding_needed else retval
  31. @staticmethod
  32. def escape_line_feed(strval, indent=' '):
  33. return strval.replace(r'\n', '\\n"\\\n' + indent + '"')
  34. @staticmethod
  35. def escape_trigraphs(strval):
  36. return strval.replace(r'?', '\\?')
  37. @staticmethod
  38. def escaped_define(strkey, val):
  39. name = "#define " + strkey + " "
  40. if _Formatting.is_str(val):
  41. define = (
  42. "\""
  43. + _Formatting.escape_line_feed(_Formatting.escape_trigraphs(_Formatting.escape_special_symbols(val)))
  44. + "\""
  45. )
  46. else:
  47. define = str(val)
  48. return name + define
  49. @staticmethod
  50. def escaped_go_map_key(strkey, strval):
  51. if _Formatting.is_str(strval):
  52. return ' ' + '"' + strkey + '": "' + _Formatting.escape_special_symbols(strval) + '",'
  53. else:
  54. return ' ' + '"' + strkey + '": "' + str(strval) + '",'
  55. def get_default_json():
  56. return json.loads(
  57. '''{
  58. "ARCADIA_SOURCE_HG_HASH": "0000000000000000000000000000000000000000",
  59. "ARCADIA_SOURCE_LAST_AUTHOR": "<UNKNOWN>",
  60. "ARCADIA_SOURCE_LAST_CHANGE": -1,
  61. "ARCADIA_SOURCE_PATH": "/",
  62. "ARCADIA_SOURCE_REVISION": -1,
  63. "ARCADIA_SOURCE_URL": "",
  64. "BRANCH": "unknown-vcs-branch",
  65. "BUILD_DATE": "",
  66. "BUILD_TIMESTAMP": 0,
  67. "BUILD_HOST": "localhost",
  68. "BUILD_USER": "nobody",
  69. "CUSTOM_VERSION": "",
  70. "RELEASE_VERSION": "",
  71. "PROGRAM_VERSION": "Arc info:\\n Branch: unknown-vcs-branch\\n Commit: 0000000000000000000000000000000000000000\\n Author: <UNKNOWN>\\n Summary: No VCS\\n\\n",
  72. "SCM_DATA": "Arc info:\\n Branch: unknown-vcs-branch\\n Commit: 0000000000000000000000000000000000000000\\n Author: <UNKNOWN>\\n Summary: No VCS\\n",
  73. "VCS": "arc",
  74. "ARCADIA_PATCH_NUMBER": 0,
  75. "ARCADIA_TAG": ""
  76. }'''
  77. )
  78. def get_json(file_name):
  79. try:
  80. with open(file_name, 'rt', encoding="utf-8") as f:
  81. out = json.load(f)
  82. # TODO: check 'tar+svn' parsing
  83. for num_var in ['ARCADIA_SOURCE_REVISION', 'ARCADIA_SOURCE_LAST_CHANGE', 'SVN_REVISION']:
  84. if num_var in out and _Formatting.is_str(out[num_var]):
  85. try:
  86. out[num_var] = int(out[num_var])
  87. except:
  88. out[num_var] = -1
  89. return out
  90. except:
  91. return get_default_json()
  92. def print_c(json_file, output_file, argv):
  93. """params:
  94. json file
  95. output file
  96. $(SOURCE_ROOT)/build/scripts/c_templates/svn_interface.c"""
  97. interface = argv[0]
  98. with open(interface, 'rt', encoding="utf-8") as c:
  99. c_file = c.read()
  100. with open(output_file, 'wt', encoding="utf-8") as f:
  101. header = '\n'.join(_Formatting.escaped_define(k, v) for k, v in json_file.items())
  102. f.write(header + '\n' + c_file)
  103. def merge_java_content(old_content, json_file):
  104. new_content, names = print_java_mf(json_file)
  105. def split_to_sections(content):
  106. sections = []
  107. cur_section = []
  108. for l in content:
  109. if l.rstrip():
  110. cur_section.append(l)
  111. else:
  112. sections.append(cur_section)
  113. cur_section = []
  114. if cur_section: # should not be needed according to format specification
  115. sections.append(cur_section)
  116. return sections
  117. def drop_duplicate_entries(main_section, names):
  118. header = re.compile('^([A-Za-z0-9][A-Za-z0-9_-]*): .*$')
  119. new_main_section = []
  120. for l in main_section:
  121. match = header.match(l)
  122. # duplicate entry
  123. if match:
  124. skip = match.group(1) in names
  125. if not skip:
  126. new_main_section.append(l)
  127. return new_main_section
  128. if old_content:
  129. sections = split_to_sections(old_content)
  130. sections[0] = drop_duplicate_entries(sections[0], names)
  131. else:
  132. sections = [['Manifest-Version: 1.0\n']]
  133. sections[0].extend(map(lambda x: x + '\n', new_content))
  134. return ''.join(map(lambda x: ''.join(x), sections)) + '\n'
  135. def merge_java_mf_jar(json_file, out_manifest, jar_file):
  136. try:
  137. temp_dir = tempfile.mkdtemp()
  138. try:
  139. with zipfile.ZipFile(jar_file, 'r') as jar:
  140. jar.extract(os.path.join('META-INF', 'MANIFEST.MF'), path=temp_dir)
  141. except KeyError:
  142. pass
  143. merge_java_mf_dir(json_file, out_manifest, temp_dir)
  144. finally:
  145. shutil.rmtree(temp_dir)
  146. def merge_java_mf_dir(json_file, out_manifest, input_dir):
  147. manifest = os.path.join(input_dir, 'META-INF', 'MANIFEST.MF')
  148. old_lines = []
  149. if os.path.isfile(manifest):
  150. with open(manifest, 'rt', encoding="utf-8") as f:
  151. old_lines = f.readlines()
  152. with open(out_manifest, 'wt', encoding="utf-8") as f:
  153. f.write(merge_java_content(old_lines, json_file))
  154. def merge_java_mf(json_file, out_manifest, input):
  155. if zipfile.is_zipfile(input):
  156. merge_java_mf_jar(json_file, out_manifest, input)
  157. elif os.path.isdir(input):
  158. merge_java_mf_dir(json_file, out_manifest, input)
  159. def print_java_mf(info):
  160. wrapper = textwrap.TextWrapper(
  161. subsequent_indent=' ', break_long_words=True, replace_whitespace=False, drop_whitespace=False
  162. )
  163. names = set()
  164. def wrap(key, val):
  165. names.add(key[:-2])
  166. if not val:
  167. return []
  168. return wrapper.wrap(key + val)
  169. lines = wrap('Program-Version-String: ', base64.b64encode(info['PROGRAM_VERSION'].encode('utf-8')).decode('utf-8'))
  170. lines += wrap('SCM-String: ', base64.b64encode(info['SCM_DATA'].encode('utf-8')).decode('utf-8'))
  171. lines += wrap('Arcadia-Source-Path: ', info['ARCADIA_SOURCE_PATH'])
  172. lines += wrap('Arcadia-Source-URL: ', info['ARCADIA_SOURCE_URL'])
  173. lines += wrap('Arcadia-Source-Revision: ', str(info['ARCADIA_SOURCE_REVISION']))
  174. lines += wrap('Arcadia-Source-Hash: ', info['ARCADIA_SOURCE_HG_HASH'].rstrip())
  175. lines += wrap('Arcadia-Source-Last-Change: ', str(info['ARCADIA_SOURCE_LAST_CHANGE']))
  176. lines += wrap('Arcadia-Source-Last-Author: ', info['ARCADIA_SOURCE_LAST_AUTHOR'])
  177. lines += wrap('Build-User: ', info['BUILD_USER'])
  178. lines += wrap('Build-Host: ', info['BUILD_HOST'])
  179. lines += wrap('Version-Control-System: ', info['VCS'])
  180. lines += wrap('Branch: ', info['BRANCH'])
  181. lines += wrap('Arcadia-Tag: ', info.get('ARCADIA_TAG', ''))
  182. lines += wrap('Arcadia-Patch-Number: ', str(info.get('ARCADIA_PATCH_NUMBER', 42)))
  183. if 'SVN_REVISION' in info:
  184. lines += wrap('SVN-Revision: ', str(info['SVN_REVISION']))
  185. lines += wrap('SVN-Arcroot: ', info['SVN_ARCROOT'])
  186. lines += wrap('SVN-Time: ', info['SVN_TIME'])
  187. lines += wrap('Build-Date: ', info['BUILD_DATE'])
  188. if 'BUILD_TIMESTAMP' in info:
  189. lines += wrap('Build-Timestamp: ', str(info['BUILD_TIMESTAMP']))
  190. if 'CUSTOM_VERSION' in info:
  191. lines += wrap(
  192. 'Custom-Version-String: ', base64.b64encode(info['CUSTOM_VERSION'].encode('utf-8')).decode('utf-8')
  193. )
  194. if 'RELEASE_VERSION' in info:
  195. lines += wrap(
  196. 'Release-Version-String: ', base64.b64encode(info['RELEASE_VERSION'].encode('utf-8')).decode('utf-8')
  197. )
  198. return lines, names
  199. def print_java(json_file, output_file, argv):
  200. """params:
  201. json file
  202. output file
  203. file"""
  204. input = argv[0] if argv else os.curdir
  205. merge_java_mf(json_file, output_file, input)
  206. def print_go(json_file, output_file, arc_project_prefix):
  207. def gen_map(info):
  208. lines = []
  209. for k, v in info.items():
  210. lines.append(_Formatting.escaped_go_map_key(k, v))
  211. return lines
  212. with open(output_file, 'wt', encoding="utf-8") as f:
  213. f.write(
  214. '\n'.join(
  215. [
  216. '// Code generated by vcs_info.py; DO NOT EDIT.',
  217. '',
  218. 'package main',
  219. 'import "{}library/go/core/buildinfo"'.format(arc_project_prefix),
  220. 'func init() {',
  221. ' buildinfo.InitBuildInfo(map[string]string {',
  222. ]
  223. + gen_map(json_file)
  224. + ['})', '}']
  225. )
  226. + '\n'
  227. )
  228. def print_json(json_file, output_file):
  229. MANDATOTRY_FIELDS_MAP = {
  230. 'ARCADIA_TAG': 'Arcadia-Tag',
  231. 'ARCADIA_PATCH_NUMBER': 'Arcadia-Patch-Number',
  232. 'ARCADIA_SOURCE_URL': 'Arcadia-Source-URL',
  233. 'ARCADIA_SOURCE_REVISION': 'Arcadia-Source-Revision',
  234. 'ARCADIA_SOURCE_HG_HASH': 'Arcadia-Source-Hash',
  235. 'ARCADIA_SOURCE_LAST_CHANGE': 'Arcadia-Source-Last-Change',
  236. 'ARCADIA_SOURCE_LAST_AUTHOR': 'Arcadia-Source-Last-Author',
  237. 'BRANCH': 'Branch',
  238. 'BUILD_HOST': 'Build-Host',
  239. 'BUILD_USER': 'Build-User',
  240. 'PROGRAM_VERSION': 'Program-Version-String',
  241. 'SCM_DATA': 'SCM-String',
  242. 'VCS': 'Version-Control-System',
  243. }
  244. SVN_REVISION = 'SVN_REVISION'
  245. SVN_FIELDS_MAP = {
  246. SVN_REVISION: 'SVN-Revision',
  247. 'SVN_ARCROOT': 'SVN-Arcroot',
  248. 'SVN_TIME': 'SVN-Time',
  249. }
  250. OPTIONAL_FIELDS_MAP = {
  251. 'BUILD_TIMESTAMP': 'Build-Timestamp',
  252. 'CUSTOM_VERSION': 'Custom-Version-String',
  253. 'RELEASE_VERSION': 'Release-Version-String',
  254. 'DIRTY': 'Working-Copy-State',
  255. }
  256. ext_json = {}
  257. for k in MANDATOTRY_FIELDS_MAP:
  258. ext_json[MANDATOTRY_FIELDS_MAP[k]] = json_file[k]
  259. if SVN_REVISION in json_file:
  260. for k in SVN_FIELDS_MAP:
  261. ext_json[SVN_FIELDS_MAP[k]] = json_file[k]
  262. for k in OPTIONAL_FIELDS_MAP:
  263. if k in json_file and json_file[k]:
  264. ext_json[OPTIONAL_FIELDS_MAP[k]] = json_file[k]
  265. with open(output_file, 'wt', encoding="utf-8") as f:
  266. json.dump(ext_json, f, sort_keys=True, indent=4)
  267. if __name__ == '__main__':
  268. if 'output-go' in sys.argv:
  269. lang = 'Go'
  270. sys.argv.remove('output-go')
  271. elif 'output-java' in sys.argv:
  272. lang = 'Java'
  273. sys.argv.remove('output-java')
  274. elif 'output-json' in sys.argv:
  275. lang = 'JSON'
  276. sys.argv.remove('output-json')
  277. else:
  278. lang = 'C'
  279. if 'no-vcs' in sys.argv:
  280. sys.argv.remove('no-vcs')
  281. json_file = get_default_json()
  282. else:
  283. json_name = sys.argv[1]
  284. json_file = get_json(json_name)
  285. if lang == 'Go':
  286. print_go(json_file, sys.argv[2], sys.argv[3])
  287. elif lang == 'Java':
  288. print_java(json_file, sys.argv[2], sys.argv[3:])
  289. elif lang == 'JSON':
  290. print_json(json_file, sys.argv[2])
  291. else:
  292. print_c(json_file, sys.argv[2], sys.argv[3:])