All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
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.
7 # This file is released into the public domain. Generated by
8 # versioneer-0.18 (https://github.com/warner/python-versioneer)
10 """Git implementation of _version.py."""
20 """Get the keywords needed to look up the version information."""
21 # these strings will be replaced by git during git-archive.
22 # setup.py/versioneer.py will grep for the variable names, so they must
23 # each be defined on a line of their own. _version.py will just call
25 git_refnames = "$Format:%d$"
26 git_full = "$Format:%H$"
27 git_date = "$Format:%ci$"
28 keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
32 class VersioneerConfig:
33 """Container for Versioneer configuration parameters."""
37 """Create, populate and return the VersioneerConfig() object."""
38 # these strings are filled in when 'setup.py versioneer' creates
40 cfg = VersioneerConfig()
44 cfg.parentdir_prefix = "None"
45 cfg.versionfile_source = "_version.py"
50 class NotThisMethod(Exception):
51 """Exception raised if a method is not valid for the current scenario."""
58 def register_vcs_handler(vcs, method): # decorator
59 """Decorator to mark a method as the handler for a particular VCS."""
62 """Store f in HANDLERS[vcs][method]."""
63 if vcs not in HANDLERS:
65 HANDLERS[vcs][method] = f
71 def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
72 """Call the given command(s)."""
73 assert isinstance(commands, list)
77 dispcmd = str([c] + args)
78 # remember shell=False, so use git.cmd on windows, not just git
83 stdout=subprocess.PIPE,
84 stderr=(subprocess.PIPE if hide_stderr else None),
87 except EnvironmentError:
89 if e.errno == errno.ENOENT:
92 print("unable to run %s" % dispcmd)
97 print("unable to find command, tried %s" % (commands,))
99 stdout = p.communicate()[0].strip()
100 if sys.version_info[0] >= 3:
101 stdout = stdout.decode()
102 if p.returncode != 0:
104 print("unable to run %s (error)" % dispcmd)
105 print("stdout was %s" % stdout)
106 return None, p.returncode
107 return stdout, p.returncode
110 def versions_from_parentdir(parentdir_prefix, root, verbose):
111 """Try to determine the version from the parent directory name.
113 Source tarballs conventionally unpack into a directory that includes both
114 the project name and a version string. We will also support searching up
115 two directory levels for an appropriately named parent directory
120 dirname = os.path.basename(root)
121 if dirname.startswith(parentdir_prefix):
123 "version": dirname[len(parentdir_prefix) :],
124 "full-revisionid": None,
130 rootdirs.append(root)
131 root = os.path.dirname(root) # up a level
135 "Tried directories %s but none started with prefix %s"
136 % (str(rootdirs), parentdir_prefix)
138 raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
141 @register_vcs_handler("git", "get_keywords")
142 def git_get_keywords(versionfile_abs):
143 """Extract version information from the given file."""
144 # the code embedded in _version.py can just fetch the value of these
145 # keywords. When used from setup.py, we don't want to import _version.py,
146 # so we do it with a regexp instead. This function is not used from
150 f = open(versionfile_abs, "r")
151 for line in f.readlines():
152 if line.strip().startswith("git_refnames ="):
153 mo = re.search(r'=\s*"(.*)"', line)
155 keywords["refnames"] = mo.group(1)
156 if line.strip().startswith("git_full ="):
157 mo = re.search(r'=\s*"(.*)"', line)
159 keywords["full"] = mo.group(1)
160 if line.strip().startswith("git_date ="):
161 mo = re.search(r'=\s*"(.*)"', line)
163 keywords["date"] = mo.group(1)
165 except EnvironmentError:
170 @register_vcs_handler("git", "keywords")
171 def git_versions_from_keywords(keywords, tag_prefix, verbose):
172 """Get version information from git keywords."""
174 raise NotThisMethod("no keywords at all, weird")
175 date = keywords.get("date")
177 # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
178 # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
179 # -like" string, which we must then edit to make compliant), because
180 # it's been around since git-1.5.3, and it's too difficult to
181 # discover which version we're using, or to work around using an
183 date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
184 refnames = keywords["refnames"].strip()
185 if refnames.startswith("$Format"):
187 print("keywords are unexpanded, not using")
188 raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
189 refs = set([r.strip() for r in refnames.strip("()").split(",")])
190 # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
191 # just "foo-1.0". If we see a "tag: " prefix, prefer those.
193 tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)])
195 # Either we're using git < 1.8.3, or there really are no tags. We use
196 # a heuristic: assume all version tags have a digit. The old git %d
197 # expansion behaves like git log --decorate=short and strips out the
198 # refs/heads/ and refs/tags/ prefixes that would let us distinguish
199 # between branches and tags. By ignoring refnames without digits, we
200 # filter out many common branch names like "release" and
201 # "stabilization", as well as "HEAD" and "master".
202 tags = set([r for r in refs if re.search(r"\d", r)])
204 print("discarding '%s', no digits" % ",".join(refs - tags))
206 print("likely tags: %s" % ",".join(sorted(tags)))
207 for ref in sorted(tags):
208 # sorting will prefer e.g. "2.0" over "2.0rc1"
209 if ref.startswith(tag_prefix):
210 r = ref[len(tag_prefix) :]
212 print("picking %s" % r)
215 "full-revisionid": keywords["full"].strip(),
220 # no suitable tags, so version is "0+unknown", but full hex is still there
222 print("no suitable tags, using unknown + full revision id")
224 "version": "0+unknown",
225 "full-revisionid": keywords["full"].strip(),
227 "error": "no suitable tags",
232 @register_vcs_handler("git", "pieces_from_vcs")
233 def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
234 """Get version from 'git describe' in the root of the source tree.
236 This only gets called if the git-archive 'subst' keywords were *not*
237 expanded, and _version.py hasn't already been rewritten with a short
238 version string, meaning we're inside a checked out source tree.
241 if sys.platform == "win32":
242 GITS = ["git.cmd", "git.exe"]
244 out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True)
247 print("Directory %s not under git control" % root)
248 raise NotThisMethod("'git rev-parse --git-dir' returned error")
250 # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
251 # if there isn't one, this yields HEX[-dirty] (no NUM)
252 describe_out, rc = run_command(
265 # --long was added in git-1.5.5
266 if describe_out is None:
267 raise NotThisMethod("'git describe' failed")
268 describe_out = describe_out.strip()
269 full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
271 raise NotThisMethod("'git rev-parse' failed")
272 full_out = full_out.strip()
275 pieces["long"] = full_out
276 pieces["short"] = full_out[:7] # maybe improved later
277 pieces["error"] = None
279 # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
280 # TAG might have hyphens.
281 git_describe = describe_out
283 # look for -dirty suffix
284 dirty = git_describe.endswith("-dirty")
285 pieces["dirty"] = dirty
287 git_describe = git_describe[: git_describe.rindex("-dirty")]
289 # now we have TAG-NUM-gHEX or HEX
291 if "-" in git_describe:
293 mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
295 # unparseable. Maybe git-describe is misbehaving?
296 pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
300 full_tag = mo.group(1)
301 if not full_tag.startswith(tag_prefix):
303 fmt = "tag '%s' doesn't start with prefix '%s'"
304 print(fmt % (full_tag, tag_prefix))
305 pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
310 pieces["closest-tag"] = full_tag[len(tag_prefix) :]
312 # distance: number of commits since tag
313 pieces["distance"] = int(mo.group(2))
315 # commit: short hex revision ID
316 pieces["short"] = mo.group(3)
320 pieces["closest-tag"] = None
321 count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root)
322 pieces["distance"] = int(count_out) # total number of commits
324 # commit date: see ISO-8601 comment in git_versions_from_keywords()
325 date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[
328 pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
333 def plus_or_dot(pieces):
334 """Return a + if we don't already have one, else return a ."""
335 if "+" in pieces.get("closest-tag", ""):
340 def render_pep440(pieces):
341 """Build up version string, with post-release "local version identifier".
343 Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
344 get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
347 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
349 if pieces["closest-tag"]:
350 rendered = pieces["closest-tag"]
351 if pieces["distance"] or pieces["dirty"]:
352 rendered += plus_or_dot(pieces)
353 rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
358 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
364 def render_pep440_pre(pieces):
365 """TAG[.post.devDISTANCE] -- No -dirty.
368 1: no tags. 0.post.devDISTANCE
370 if pieces["closest-tag"]:
371 rendered = pieces["closest-tag"]
372 if pieces["distance"]:
373 rendered += ".post.dev%d" % pieces["distance"]
376 rendered = "0.post.dev%d" % pieces["distance"]
380 def render_pep440_post(pieces):
381 """TAG[.postDISTANCE[.dev0]+gHEX] .
383 The ".dev0" means dirty. Note that .dev0 sorts backwards
384 (a dirty tree will appear "older" than the corresponding clean one),
385 but you shouldn't be releasing software with -dirty anyways.
388 1: no tags. 0.postDISTANCE[.dev0]
390 if pieces["closest-tag"]:
391 rendered = pieces["closest-tag"]
392 if pieces["distance"] or pieces["dirty"]:
393 rendered += ".post%d" % pieces["distance"]
396 rendered += plus_or_dot(pieces)
397 rendered += "g%s" % pieces["short"]
400 rendered = "0.post%d" % pieces["distance"]
403 rendered += "+g%s" % pieces["short"]
407 def render_pep440_old(pieces):
408 """TAG[.postDISTANCE[.dev0]] .
410 The ".dev0" means dirty.
413 1: no tags. 0.postDISTANCE[.dev0]
415 if pieces["closest-tag"]:
416 rendered = pieces["closest-tag"]
417 if pieces["distance"] or pieces["dirty"]:
418 rendered += ".post%d" % pieces["distance"]
423 rendered = "0.post%d" % pieces["distance"]
429 def render_git_describe(pieces):
430 """TAG[-DISTANCE-gHEX][-dirty].
432 Like 'git describe --tags --dirty --always'.
435 1: no tags. HEX[-dirty] (note: no 'g' prefix)
437 if pieces["closest-tag"]:
438 rendered = pieces["closest-tag"]
439 if pieces["distance"]:
440 rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
443 rendered = pieces["short"]
449 def render_git_describe_long(pieces):
450 """TAG-DISTANCE-gHEX[-dirty].
452 Like 'git describe --tags --dirty --always -long'.
453 The distance/hash is unconditional.
456 1: no tags. HEX[-dirty] (note: no 'g' prefix)
458 if pieces["closest-tag"]:
459 rendered = pieces["closest-tag"]
460 rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
463 rendered = pieces["short"]
469 def render(pieces, style):
470 """Render the given version pieces into the requested style."""
473 "version": "unknown",
474 "full-revisionid": pieces.get("long"),
476 "error": pieces["error"],
480 if not style or style == "default":
481 style = "pep440" # the default
483 if style == "pep440":
484 rendered = render_pep440(pieces)
485 elif style == "pep440-pre":
486 rendered = render_pep440_pre(pieces)
487 elif style == "pep440-post":
488 rendered = render_pep440_post(pieces)
489 elif style == "pep440-old":
490 rendered = render_pep440_old(pieces)
491 elif style == "git-describe":
492 rendered = render_git_describe(pieces)
493 elif style == "git-describe-long":
494 rendered = render_git_describe_long(pieces)
496 raise ValueError("unknown style '%s'" % style)
500 "full-revisionid": pieces["long"],
501 "dirty": pieces["dirty"],
503 "date": pieces.get("date"),
508 """Get version information or return default if unable to do so."""
509 # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
510 # __file__, we can work backwards from there to the root. Some
511 # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
512 # case we can only use expanded keywords.
515 verbose = cfg.verbose
518 return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
519 except NotThisMethod:
523 root = os.path.realpath(__file__)
524 # versionfile_source is the relative path from the top of the source
525 # tree (where the .git directory might live) to this file. Invert
526 # this to find the root from __file__.
527 for i in cfg.versionfile_source.split("/"):
528 root = os.path.dirname(root)
531 "version": "0+unknown",
532 "full-revisionid": None,
534 "error": "unable to find root of source tree",
539 pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
540 return render(pieces, cfg.style)
541 except NotThisMethod:
545 if cfg.parentdir_prefix:
546 return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
547 except NotThisMethod:
551 "version": "0+unknown",
552 "full-revisionid": None,
554 "error": "unable to compute version",