_version.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. # This file helps to compute a version number in source trees obtained from
  2. # git-archive tarball (such as those provided by githubs download-from-tag
  3. # feature). Distribution tarballs (built by setup.py sdist) and build
  4. # directories (produced by setup.py build) will contain a much shorter file
  5. # that just contains the computed version number.
  6. # This file is released into the public domain. Generated by
  7. # versioneer-0.14 (https://github.com/warner/python-versioneer)
  8. import errno
  9. import os
  10. import re
  11. import subprocess
  12. import sys
  13. # these strings will be replaced by git during git-archive
  14. git_refnames = "$Format:%d$"
  15. git_full = "$Format:%H$"
  16. # these strings are filled in when 'setup.py versioneer' creates _version.py
  17. tag_prefix = ""
  18. parentdir_prefix = "borgbackup-"
  19. versionfile_source = "attic/_version.py"
  20. def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
  21. assert isinstance(commands, list)
  22. p = None
  23. for c in commands:
  24. try:
  25. # remember shell=False, so use git.cmd on windows, not just git
  26. p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
  27. stderr=(subprocess.PIPE if hide_stderr
  28. else None))
  29. break
  30. except EnvironmentError:
  31. e = sys.exc_info()[1]
  32. if e.errno == errno.ENOENT:
  33. continue
  34. if verbose:
  35. print("unable to run %s" % args[0])
  36. print(e)
  37. return None
  38. else:
  39. if verbose:
  40. print("unable to find command, tried %s" % (commands,))
  41. return None
  42. stdout = p.communicate()[0].strip()
  43. if sys.version_info[0] >= 3:
  44. stdout = stdout.decode()
  45. if p.returncode != 0:
  46. if verbose:
  47. print("unable to run %s (error)" % args[0])
  48. return None
  49. return stdout
  50. def versions_from_parentdir(parentdir_prefix, root, verbose=False):
  51. # Source tarballs conventionally unpack into a directory that includes
  52. # both the project name and a version string.
  53. dirname = os.path.basename(root)
  54. if not dirname.startswith(parentdir_prefix):
  55. if verbose:
  56. print("guessing rootdir is '%s', but '%s' doesn't start with "
  57. "prefix '%s'" % (root, dirname, parentdir_prefix))
  58. return None
  59. return {"version": dirname[len(parentdir_prefix):], "full": ""}
  60. def git_get_keywords(versionfile_abs):
  61. # the code embedded in _version.py can just fetch the value of these
  62. # keywords. When used from setup.py, we don't want to import _version.py,
  63. # so we do it with a regexp instead. This function is not used from
  64. # _version.py.
  65. keywords = {}
  66. try:
  67. f = open(versionfile_abs, "r")
  68. for line in f.readlines():
  69. if line.strip().startswith("git_refnames ="):
  70. mo = re.search(r'=\s*"(.*)"', line)
  71. if mo:
  72. keywords["refnames"] = mo.group(1)
  73. if line.strip().startswith("git_full ="):
  74. mo = re.search(r'=\s*"(.*)"', line)
  75. if mo:
  76. keywords["full"] = mo.group(1)
  77. f.close()
  78. except EnvironmentError:
  79. pass
  80. return keywords
  81. def git_versions_from_keywords(keywords, tag_prefix, verbose=False):
  82. if not keywords:
  83. return {} # keyword-finding function failed to find keywords
  84. refnames = keywords["refnames"].strip()
  85. if refnames.startswith("$Format"):
  86. if verbose:
  87. print("keywords are unexpanded, not using")
  88. return {} # unexpanded, so not in an unpacked git-archive tarball
  89. refs = set([r.strip() for r in refnames.strip("()").split(",")])
  90. # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
  91. # just "foo-1.0". If we see a "tag: " prefix, prefer those.
  92. TAG = "tag: "
  93. tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
  94. if not tags:
  95. # Either we're using git < 1.8.3, or there really are no tags. We use
  96. # a heuristic: assume all version tags have a digit. The old git %d
  97. # expansion behaves like git log --decorate=short and strips out the
  98. # refs/heads/ and refs/tags/ prefixes that would let us distinguish
  99. # between branches and tags. By ignoring refnames without digits, we
  100. # filter out many common branch names like "release" and
  101. # "stabilization", as well as "HEAD" and "master".
  102. tags = set([r for r in refs if re.search(r'\d', r)])
  103. if verbose:
  104. print("discarding '%s', no digits" % ",".join(refs-tags))
  105. if verbose:
  106. print("likely tags: %s" % ",".join(sorted(tags)))
  107. for ref in sorted(tags):
  108. # sorting will prefer e.g. "2.0" over "2.0rc1"
  109. if ref.startswith(tag_prefix):
  110. r = ref[len(tag_prefix):]
  111. if verbose:
  112. print("picking %s" % r)
  113. return {"version": r,
  114. "full": keywords["full"].strip()}
  115. # no suitable tags, so version is "0+unknown", but full hex is still there
  116. if verbose:
  117. print("no suitable tags, using unknown + full revision id")
  118. return {"version": "0+unknown",
  119. "full": keywords["full"].strip()}
  120. def git_parse_vcs_describe(git_describe, tag_prefix, verbose=False):
  121. # TAG-NUM-gHEX[-dirty] or HEX[-dirty] . TAG might have hyphens.
  122. # dirty
  123. dirty = git_describe.endswith("-dirty")
  124. if dirty:
  125. git_describe = git_describe[:git_describe.rindex("-dirty")]
  126. dirty_suffix = ".dirty" if dirty else ""
  127. # now we have TAG-NUM-gHEX or HEX
  128. if "-" not in git_describe: # just HEX
  129. return "0+untagged.g"+git_describe+dirty_suffix, dirty
  130. # just TAG-NUM-gHEX
  131. mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
  132. if not mo:
  133. # unparseable. Maybe git-describe is misbehaving?
  134. return "0+unparseable"+dirty_suffix, dirty
  135. # tag
  136. full_tag = mo.group(1)
  137. if not full_tag.startswith(tag_prefix):
  138. if verbose:
  139. fmt = "tag '%s' doesn't start with prefix '%s'"
  140. print(fmt % (full_tag, tag_prefix))
  141. return None, dirty
  142. tag = full_tag[len(tag_prefix):]
  143. # distance: number of commits since tag
  144. distance = int(mo.group(2))
  145. # commit: short hex revision ID
  146. commit = mo.group(3)
  147. # now build up version string, with post-release "local version
  148. # identifier". Our goal: TAG[+NUM.gHEX[.dirty]] . Note that if you get a
  149. # tagged build and then dirty it, you'll get TAG+0.gHEX.dirty . So you
  150. # can always test version.endswith(".dirty").
  151. version = tag
  152. if distance or dirty:
  153. version += "+%d.g%s" % (distance, commit) + dirty_suffix
  154. return version, dirty
  155. def git_versions_from_vcs(tag_prefix, root, verbose=False):
  156. # this runs 'git' from the root of the source tree. This only gets called
  157. # if the git-archive 'subst' keywords were *not* expanded, and
  158. # _version.py hasn't already been rewritten with a short version string,
  159. # meaning we're inside a checked out source tree.
  160. if not os.path.exists(os.path.join(root, ".git")):
  161. if verbose:
  162. print("no .git in %s" % root)
  163. return {} # get_versions() will try next method
  164. GITS = ["git"]
  165. if sys.platform == "win32":
  166. GITS = ["git.cmd", "git.exe"]
  167. # if there is a tag, this yields TAG-NUM-gHEX[-dirty]
  168. # if there are no tags, this yields HEX[-dirty] (no NUM)
  169. stdout = run_command(GITS, ["describe", "--tags", "--dirty",
  170. "--always", "--long"],
  171. cwd=root)
  172. # --long was added in git-1.5.5
  173. if stdout is None:
  174. return {} # try next method
  175. version, dirty = git_parse_vcs_describe(stdout, tag_prefix, verbose)
  176. # build "full", which is FULLHEX[.dirty]
  177. stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
  178. if stdout is None:
  179. return {}
  180. full = stdout.strip()
  181. if dirty:
  182. full += ".dirty"
  183. return {"version": version, "full": full}
  184. def get_versions(default={"version": "0+unknown", "full": ""}, verbose=False):
  185. # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
  186. # __file__, we can work backwards from there to the root. Some
  187. # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
  188. # case we can only use expanded keywords.
  189. keywords = {"refnames": git_refnames, "full": git_full}
  190. ver = git_versions_from_keywords(keywords, tag_prefix, verbose)
  191. if ver:
  192. return ver
  193. try:
  194. root = os.path.realpath(__file__)
  195. # versionfile_source is the relative path from the top of the source
  196. # tree (where the .git directory might live) to this file. Invert
  197. # this to find the root from __file__.
  198. for i in versionfile_source.split('/'):
  199. root = os.path.dirname(root)
  200. except NameError:
  201. return default
  202. return (git_versions_from_vcs(tag_prefix, root, verbose)
  203. or versions_from_parentdir(parentdir_prefix, root, verbose)
  204. or default)