vcs_info.py 11 KB

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