generate_vcs_info.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. # coding: utf-8
  2. import json
  3. import locale
  4. import re
  5. import os
  6. import subprocess
  7. import sys
  8. import time
  9. INDENT = " " * 4
  10. def _get_vcs_dictionary(vcs_type, *arg):
  11. if vcs_type == 'git':
  12. return _GitVersion.parse(*arg)
  13. else:
  14. raise Exception("Unknown VCS type {}".format(str(vcs_type)))
  15. def _get_user_locale():
  16. try:
  17. return [locale.getencoding()]
  18. except Exception:
  19. return []
  20. class _GitVersion:
  21. @classmethod
  22. def parse(cls, commit_hash, author_info, summary_info, body_info, tag_info, branch_info, depth=None):
  23. r"""Parses output of
  24. git rev-parse HEAD
  25. git log -1 --format='format:%an <%ae>'
  26. git log -1 --format='format:%s'
  27. git log -1 --grep='^git-svn-id: ' --format='format:%b' or
  28. git log -1 --grep='^Revision: r?\d*' --format='format:%b
  29. git describe --exact-match --tags HEAD
  30. git describe --exact-match --all HEAD
  31. and depth as computed by _get_git_depth
  32. '"""
  33. info = {}
  34. info['hash'] = commit_hash
  35. info['commit_author'] = _SystemInfo._to_text(author_info)
  36. info['summary'] = _SystemInfo._to_text(summary_info)
  37. if 'svn_commit_revision' not in info:
  38. url = re.search("git?-svn?-id: (.*)@(\\d*).*", body_info)
  39. if url:
  40. info['svn_url'] = url.group(1)
  41. info['svn_commit_revision'] = int(url.group(2))
  42. if 'svn_commit_revision' not in info:
  43. rev = re.search('Revision: r?(\\d*).*', body_info)
  44. if rev:
  45. info['svn_commit_revision'] = int(rev.group(1))
  46. info['tag'] = tag_info
  47. info['branch'] = branch_info
  48. info['scm_text'] = cls._format_scm_data(info)
  49. info['vcs'] = 'git'
  50. if depth:
  51. info['patch_number'] = int(depth)
  52. return info
  53. @staticmethod
  54. def _format_scm_data(info):
  55. scm_data = "Git info:\n"
  56. scm_data += INDENT + "Commit: " + info['hash'] + "\n"
  57. scm_data += INDENT + "Branch: " + info['branch'] + "\n"
  58. scm_data += INDENT + "Author: " + info['commit_author'] + "\n"
  59. scm_data += INDENT + "Summary: " + info['summary'] + "\n"
  60. if 'svn_commit_revision' in info or 'svn_url' in info:
  61. scm_data += INDENT + "git-svn info:\n"
  62. if 'svn_url' in info:
  63. scm_data += INDENT + "URL: " + info['svn_url'] + "\n"
  64. if 'svn_commit_revision' in info:
  65. scm_data += INDENT + "Last Changed Rev: " + str(info['svn_commit_revision']) + "\n"
  66. return scm_data
  67. @staticmethod
  68. def external_data(arc_root):
  69. env = os.environ.copy()
  70. env['TZ'] = ''
  71. hash_args = ['rev-parse', 'HEAD']
  72. author_args = ['log', '-1', '--format=format:%an <%ae>']
  73. summary_args = ['log', '-1', '--format=format:%s']
  74. svn_args = ['log', '-1', '--grep=^git-svn-id: ', '--format=format:%b']
  75. svn_args_alt = ['log', '-1', '--grep=^Revision: r\\?\\d*', '--format=format:%b']
  76. tag_args = ['describe', '--exact-match', '--tags', 'HEAD']
  77. branch_args = ['describe', '--exact-match', '--all', 'HEAD']
  78. # using local 'Popen' wrapper
  79. commit = _SystemInfo._system_command_call(['git'] + hash_args, env=env, cwd=arc_root).rstrip()
  80. author = _SystemInfo._system_command_call(['git'] + author_args, env=env, cwd=arc_root)
  81. commit = _SystemInfo._system_command_call(['git'] + hash_args, env=env, cwd=arc_root).rstrip()
  82. author = _SystemInfo._system_command_call(['git'] + author_args, env=env, cwd=arc_root)
  83. summary = _SystemInfo._system_command_call(['git'] + summary_args, env=env, cwd=arc_root)
  84. svn_id = _SystemInfo._system_command_call(['git'] + svn_args, env=env, cwd=arc_root)
  85. if not svn_id:
  86. svn_id = _SystemInfo._system_command_call(['git'] + svn_args_alt, env=env, cwd=arc_root)
  87. try:
  88. tag_info = _SystemInfo._system_command_call(['git'] + tag_args, env=env, cwd=arc_root).splitlines()
  89. except Exception:
  90. tag_info = [''.encode('utf-8')]
  91. try:
  92. branch_info = _SystemInfo._system_command_call(['git'] + branch_args, env=env, cwd=arc_root).splitlines()
  93. except Exception:
  94. branch_info = [''.encode('utf-8')]
  95. depth = str(_GitVersion._get_git_depth(env, arc_root)).encode('utf-8')
  96. # logger.debug('Git info commit:{}, author:{}, summary:{}, svn_id:{}'.format(commit, author, summary, svn_id))
  97. return [commit, author, summary, svn_id, tag_info[0], branch_info[0], depth]
  98. # YT's patch number.
  99. @staticmethod
  100. def _get_git_depth(env, arc_root):
  101. graph = {}
  102. full_history_args = ["log", "--full-history", "--format=%H %P", "HEAD"]
  103. history = _SystemInfo._system_command_call(['git'] + full_history_args, env=env, cwd=arc_root).decode('utf-8')
  104. head = None
  105. for line in history.splitlines():
  106. values = line.split()
  107. if values:
  108. if head is None:
  109. head = values[0]
  110. graph[values[0]] = values[1:]
  111. assert head
  112. cache = {}
  113. stack = [(head, None, False)]
  114. while stack:
  115. commit, child, calculated = stack.pop()
  116. if commit in cache:
  117. calculated = True
  118. if calculated:
  119. if child is not None:
  120. cache[child] = max(cache.get(child, 0), cache[commit] + 1)
  121. else:
  122. stack.append((commit, child, True))
  123. parents = graph[commit]
  124. if not parents:
  125. cache[commit] = 0
  126. else:
  127. for parent in parents:
  128. stack.append((parent, commit, False))
  129. return cache[head]
  130. class _SystemInfo:
  131. LOCALE_LIST = _get_user_locale() + [sys.getfilesystemencoding(), 'utf-8']
  132. @classmethod
  133. def get_locale(cls):
  134. import codecs
  135. for i in cls.LOCALE_LIST:
  136. if not i:
  137. continue
  138. try:
  139. codecs.lookup(i)
  140. return i
  141. except LookupError:
  142. continue
  143. @staticmethod
  144. def _to_text(s):
  145. if isinstance(s, bytes):
  146. return s.decode(_SystemInfo.get_locale(), errors='replace')
  147. return s
  148. @staticmethod
  149. def get_user():
  150. sys_user = os.environ.get("USER")
  151. if not sys_user:
  152. sys_user = os.environ.get("USERNAME")
  153. if not sys_user:
  154. sys_user = os.environ.get("LOGNAME")
  155. if not sys_user:
  156. sys_user = "Unknown user"
  157. return sys_user
  158. @staticmethod
  159. def get_date(stamp=None):
  160. # Format compatible with SVN-xml format.
  161. return time.strftime("%Y-%m-%dT%H:%M:%S.000000Z", time.gmtime(stamp))
  162. @staticmethod
  163. def get_timestamp():
  164. # Unix timestamp.
  165. return int(time.time())
  166. @staticmethod
  167. def get_other_data(src_dir, data_file='local.ymake'):
  168. other_data = "Other info:\n"
  169. other_data += INDENT + "Build by: " + _SystemInfo.get_user() + "\n"
  170. other_data += INDENT + "Top src dir: {}\n".format(src_dir)
  171. # logger.debug("Other data: %s", other_data)
  172. return other_data
  173. @staticmethod
  174. def _get_host_info(fake_build_info=False):
  175. if fake_build_info:
  176. host_info = '*sys localhost 1.0.0 #dummy information '
  177. elif not on_win():
  178. host_info = ' '.join(os.uname())
  179. else:
  180. host_info = _SystemInfo._system_command_call("VER") # XXX: check shell from cygwin to call VER this way!
  181. return INDENT + INDENT + host_info.strip() + "\n" if host_info else ""
  182. @staticmethod
  183. def _system_command_call(command, **kwargs):
  184. if isinstance(command, list):
  185. command = subprocess.list2cmdline(command)
  186. try:
  187. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, **kwargs)
  188. stdout, stderr = process.communicate()
  189. if process.returncode != 0:
  190. # logger.debug('{}\nRunning {} failed with exit code {}\n'.format(stderr, command, process.returncode))
  191. raise get_svn_exception()(stdout=stdout, stderr=stderr, rc=process.returncode, cmd=[command])
  192. return stdout
  193. except OSError as e:
  194. msg = e.strerror
  195. errcodes = 'error {}'.format(e.errno)
  196. if on_win() and isinstance(e, WindowsError):
  197. errcodes += ', win-error {}'.format(e.winerror)
  198. try:
  199. import ctypes
  200. msg = str(ctypes.FormatError(e.winerror), _SystemInfo.get_locale()).encode('utf-8')
  201. except ImportError:
  202. pass
  203. # logger.debug('System command call {} failed [{}]: {}\n'.format(command, errcodes, msg))
  204. return None
  205. def _get_raw_data(vcs_type, vcs_root):
  206. lines = []
  207. if vcs_type == 'git':
  208. lines = _GitVersion.external_data(vcs_root)
  209. return [l.decode('utf-8') for l in lines]
  210. def _get_json(vcs_root):
  211. try:
  212. vcs_type = "git"
  213. info = _get_vcs_dictionary(vcs_type, *_get_raw_data(vcs_type, vcs_root))
  214. return info, vcs_root
  215. except Exception:
  216. return None, ""
  217. def _dump_json(
  218. arc_root,
  219. info,
  220. other_data=None,
  221. build_user=None,
  222. build_date=None,
  223. build_timestamp=0,
  224. custom_version='',
  225. ):
  226. j = {}
  227. j['PROGRAM_VERSION'] = info['scm_text'] + "\n" + _SystemInfo._to_text(other_data)
  228. j['CUSTOM_VERSION'] = str(_SystemInfo._to_text(custom_version))
  229. j['SCM_DATA'] = info['scm_text']
  230. j['ARCADIA_SOURCE_PATH'] = _SystemInfo._to_text(arc_root)
  231. j['ARCADIA_SOURCE_URL'] = info.get('url', info.get('svn_url', ''))
  232. j['ARCADIA_SOURCE_REVISION'] = info.get('revision', -1)
  233. j['ARCADIA_SOURCE_HG_HASH'] = info.get('hash', '')
  234. j['ARCADIA_SOURCE_LAST_CHANGE'] = info.get('commit_revision', info.get('svn_commit_revision', -1))
  235. j['ARCADIA_SOURCE_LAST_AUTHOR'] = info.get('commit_author', '')
  236. j['ARCADIA_PATCH_NUMBER'] = info.get('patch_number', 0)
  237. j['BUILD_USER'] = _SystemInfo._to_text(build_user)
  238. j['VCS'] = info.get('vcs', '')
  239. j['BRANCH'] = info.get('branch', '')
  240. j['ARCADIA_TAG'] = info.get('tag', '')
  241. j['DIRTY'] = info.get('dirty', '')
  242. if 'url' in info or 'svn_url' in info:
  243. j['SVN_REVISION'] = info.get('svn_commit_revision', info.get('revision', -1))
  244. j['SVN_ARCROOT'] = info.get('url', info.get('svn_url', ''))
  245. j['SVN_TIME'] = info.get('commit_date', info.get('svn_commit_date', ''))
  246. j['BUILD_DATE'] = build_date
  247. j['BUILD_TIMESTAMP'] = build_timestamp
  248. return json.dumps(j, sort_keys=True, indent=4, separators=(',', ': '))
  249. def get_version_info(arc_root, custom_version=""):
  250. info, vcs_root = _get_json(arc_root)
  251. if info is None:
  252. return ""
  253. return _dump_json(
  254. vcs_root,
  255. info,
  256. other_data=_SystemInfo.get_other_data(
  257. src_dir=vcs_root,
  258. ),
  259. build_user=_SystemInfo.get_user(),
  260. build_date=_SystemInfo.get_date(None),
  261. build_timestamp=_SystemInfo.get_timestamp(),
  262. custom_version=custom_version,
  263. )
  264. if __name__ == '__main__':
  265. with open(sys.argv[1], 'wt', encoding="utf-8") as f:
  266. f.write(get_version_info(sys.argv[2]))