_version.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. IN_LONG_VERSION_PY = True
  2. # This file helps to compute a version number in source trees obtained from
  3. # git-archive tarball (such as those provided by github's download-from-tag
  4. # feature). Distribution tarballs (build by setup.py sdist) and build
  5. # directories (produced by setup.py build) will contain a much shorter file
  6. # that just contains the computed version number.
  7. # This file is released into the public domain. Generated by
  8. # versioneer-0.7+ (https://github.com/warner/python-versioneer)
  9. # these strings will be replaced by git during git-archive
  10. git_refnames = "$Format:%d$"
  11. git_full = "$Format:%H$"
  12. import subprocess
  13. def run_command(args, cwd=None, verbose=False):
  14. try:
  15. # remember shell=False, so use git.cmd on windows, not just git
  16. p = subprocess.Popen(args, stdout=subprocess.PIPE, cwd=cwd)
  17. except EnvironmentError:
  18. e = sys.exc_info()[1]
  19. if verbose:
  20. print("unable to run %s" % args[0])
  21. print(e)
  22. return None
  23. stdout = p.communicate()[0].strip()
  24. if sys.version >= '3':
  25. stdout = stdout.decode()
  26. if p.returncode != 0:
  27. if verbose:
  28. print("unable to run %s (error)" % args[0])
  29. return None
  30. return stdout
  31. import sys
  32. import re
  33. import os.path
  34. def get_expanded_variables(versionfile_source):
  35. # the code embedded in _version.py can just fetch the value of these
  36. # variables. When used from setup.py, we don't want to import
  37. # _version.py, so we do it with a regexp instead. This function is not
  38. # used from _version.py.
  39. variables = {}
  40. try:
  41. for line in open(versionfile_source, "r").readlines():
  42. if line.strip().startswith("git_refnames ="):
  43. mo = re.search(r'=\s*"(.*)"', line)
  44. if mo:
  45. variables["refnames"] = mo.group(1)
  46. if line.strip().startswith("git_full ="):
  47. mo = re.search(r'=\s*"(.*)"', line)
  48. if mo:
  49. variables["full"] = mo.group(1)
  50. except EnvironmentError:
  51. pass
  52. return variables
  53. def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
  54. refnames = variables["refnames"].strip()
  55. if refnames.startswith("$Format"):
  56. if verbose:
  57. print("variables are unexpanded, not using")
  58. return {} # unexpanded, so not in an unpacked git-archive tarball
  59. refs = set([r.strip() for r in refnames.strip("()").split(",")])
  60. for ref in list(refs):
  61. if not re.search(r'\d', ref):
  62. if verbose:
  63. print("discarding '%s', no digits" % ref)
  64. refs.discard(ref)
  65. # Assume all version tags have a digit. git's %d expansion
  66. # behaves like git log --decorate=short and strips out the
  67. # refs/heads/ and refs/tags/ prefixes that would let us
  68. # distinguish between branches and tags. By ignoring refnames
  69. # without digits, we filter out many common branch names like
  70. # "release" and "stabilization", as well as "HEAD" and "master".
  71. if verbose:
  72. print("remaining refs: %s" % ",".join(sorted(refs)))
  73. for ref in sorted(refs):
  74. # sorting will prefer e.g. "2.0" over "2.0rc1"
  75. if ref.startswith(tag_prefix):
  76. r = ref[len(tag_prefix):]
  77. if verbose:
  78. print("picking %s" % r)
  79. return {"version": r,
  80. "full": variables["full"].strip()}
  81. # no suitable tags, so we use the full revision id
  82. if verbose:
  83. print("no suitable tags, using full revision id")
  84. return {"version": variables["full"].strip(),
  85. "full": variables["full"].strip()}
  86. def versions_from_vcs(tag_prefix, versionfile_source, verbose=False):
  87. # this runs 'git' from the root of the source tree. That either means
  88. # someone ran a setup.py command (and this code is in versioneer.py, so
  89. # IN_LONG_VERSION_PY=False, thus the containing directory is the root of
  90. # the source tree), or someone ran a project-specific entry point (and
  91. # this code is in _version.py, so IN_LONG_VERSION_PY=True, thus the
  92. # containing directory is somewhere deeper in the source tree). This only
  93. # gets called if the git-archive 'subst' variables were *not* expanded,
  94. # and _version.py hasn't already been rewritten with a short version
  95. # string, meaning we're inside a checked out source tree.
  96. try:
  97. here = os.path.abspath(__file__)
  98. except NameError:
  99. # some py2exe/bbfreeze/non-CPython implementations don't do __file__
  100. return {} # not always correct
  101. # versionfile_source is the relative path from the top of the source tree
  102. # (where the .git directory might live) to this file. Invert this to find
  103. # the root from __file__.
  104. root = here
  105. if IN_LONG_VERSION_PY:
  106. for i in range(len(versionfile_source.split("/"))):
  107. root = os.path.dirname(root)
  108. else:
  109. root = os.path.dirname(here)
  110. if not os.path.exists(os.path.join(root, ".git")):
  111. if verbose:
  112. print("no .git in %s" % root)
  113. return {}
  114. GIT = "git"
  115. if sys.platform == "win32":
  116. GIT = "git.cmd"
  117. stdout = run_command([GIT, "describe", "--tags", "--dirty", "--always"],
  118. cwd=root)
  119. if stdout is None:
  120. return {}
  121. if not stdout.startswith(tag_prefix):
  122. if verbose:
  123. print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix))
  124. return {}
  125. tag = stdout[len(tag_prefix):]
  126. stdout = run_command([GIT, "rev-parse", "HEAD"], cwd=root)
  127. if stdout is None:
  128. return {}
  129. full = stdout.strip()
  130. if tag.endswith("-dirty"):
  131. full += "-dirty"
  132. return {"version": tag, "full": full}
  133. def versions_from_parentdir(parentdir_prefix, versionfile_source, verbose=False):
  134. if IN_LONG_VERSION_PY:
  135. # We're running from _version.py. If it's from a source tree
  136. # (execute-in-place), we can work upwards to find the root of the
  137. # tree, and then check the parent directory for a version string. If
  138. # it's in an installed application, there's no hope.
  139. try:
  140. here = os.path.abspath(__file__)
  141. except NameError:
  142. # py2exe/bbfreeze/non-CPython don't have __file__
  143. return {} # without __file__, we have no hope
  144. # versionfile_source is the relative path from the top of the source
  145. # tree to _version.py. Invert this to find the root from __file__.
  146. root = here
  147. for i in range(len(versionfile_source.split("/"))):
  148. root = os.path.dirname(root)
  149. else:
  150. # we're running from versioneer.py, which means we're running from
  151. # the setup.py in a source tree. sys.argv[0] is setup.py in the root.
  152. here = os.path.abspath(sys.argv[0])
  153. root = os.path.dirname(here)
  154. # Source tarballs conventionally unpack into a directory that includes
  155. # both the project name and a version string.
  156. dirname = os.path.basename(root)
  157. if not dirname.startswith(parentdir_prefix):
  158. if verbose:
  159. print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" %
  160. (root, dirname, parentdir_prefix))
  161. return None
  162. return {"version": dirname[len(parentdir_prefix):], "full": ""}
  163. tag_prefix = ""
  164. parentdir_prefix = "borgbackup-"
  165. versionfile_source = "attic/_version.py"
  166. def get_versions(default={"version": "unknown", "full": ""}, verbose=False):
  167. variables = {"refnames": git_refnames, "full": git_full}
  168. ver = versions_from_expanded_variables(variables, tag_prefix, verbose)
  169. if not ver:
  170. ver = versions_from_vcs(tag_prefix, versionfile_source, verbose)
  171. if not ver:
  172. ver = versions_from_parentdir(parentdir_prefix, versionfile_source,
  173. verbose)
  174. if not ver:
  175. ver = default
  176. return ver