Debian Codegraph @

autodocsumm/_version.py

raw
1
2 # This file helps to compute a version number in source trees obtained from
3 # git-archive tarball (such as those provided by githubs download-from-tag
4 # feature). Distribution tarballs (built 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
8 # This file is released into the public domain.
9 # Generated by versioneer-0.28
10 # https://github.com/python-versioneer/python-versioneer
11
12 """Git implementation of _version.py."""
13
14 import errno
15 import os
16 import re
17 import subprocess
18 import sys
19 from typing import Callable, Dict
20 import functools
21
22
23 def get_keywords():
24 """Get the keywords needed to look up the version information."""
25 # these strings will be replaced by git during git-archive.
26 # setup.py/versioneer.py will grep for the variable names, so they must
27 # each be defined on a line of their own. _version.py will just call
28 # get_keywords().
29 git_refnames = " (grafted, HEAD, tag: v0.2.14)"
30 git_full = "f81147eff409d6de19564752c1e6182362b23e04"
31 git_date = "2024-10-21 14:26:29 +0200"
32 keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
33 return keywords
34
35
36 class VersioneerConfig:
37 """Container for Versioneer configuration parameters."""
38
39
40 def get_config():
41 """Create, populate and return the VersioneerConfig() object."""
42 # these strings are filled in when 'setup.py versioneer' creates
43 # _version.py
44 cfg = VersioneerConfig()
45 cfg.VCS = "git"
46 cfg.style = "pep440"
47 cfg.tag_prefix = "v"
48 cfg.parentdir_prefix = "autodocsumm-"
49 cfg.versionfile_source = "autodocsumm/_version.py"
50 cfg.verbose = False
51 return cfg
52
53
54 class NotThisMethod(Exception):
55 """Exception raised if a method is not valid for the current scenario."""
56
57
58 LONG_VERSION_PY: Dict[str, str] = {}
59 HANDLERS: Dict[str, Dict[str, Callable]] = {}
60
61
62 def register_vcs_handler(vcs, method): # decorator
63 """Create decorator to mark a method as the handler of a VCS."""
64 def decorate(f):
65 """Store f in HANDLERS[vcs][method]."""
66 if vcs not in HANDLERS:
67 HANDLERS[vcs] = {}
68 HANDLERS[vcs][method] = f
69 return f
70 return decorate
71
72
73 def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
74 env=None):
75 """Call the given command(s)."""
76 assert isinstance(commands, list)
77 process = None
78
79 popen_kwargs = {}
80 if sys.platform == "win32":
81 # This hides the console window if pythonw.exe is used
82 startupinfo = subprocess.STARTUPINFO()
83 startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
84 popen_kwargs["startupinfo"] = startupinfo
85
86 for command in commands:
87 try:
88 dispcmd = str([command] + args)
89 # remember shell=False, so use git.cmd on windows, not just git
90 process = subprocess.Popen([command] + args, cwd=cwd, env=env,
91 stdout=subprocess.PIPE,
92 stderr=(subprocess.PIPE if hide_stderr
93 else None), **popen_kwargs)
94 break
95 except OSError:
96 e = sys.exc_info()[1]
97 if e.errno == errno.ENOENT:
98 continue
99 if verbose:
100 print("unable to run %s" % dispcmd)
101 print(e)
102 return None, None
103 else:
104 if verbose:
105 print("unable to find command, tried %s" % (commands,))
106 return None, None
107 stdout = process.communicate()[0].strip().decode()
108 if process.returncode != 0:
109 if verbose:
110 print("unable to run %s (error)" % dispcmd)
111 print("stdout was %s" % stdout)
112 return None, process.returncode
113 return stdout, process.returncode
114
115
116 def versions_from_parentdir(parentdir_prefix, root, verbose):
117 """Try to determine the version from the parent directory name.
118
119 Source tarballs conventionally unpack into a directory that includes both
120 the project name and a version string. We will also support searching up
121 two directory levels for an appropriately named parent directory
122 """
123 rootdirs = []
124
125 for _ in range(3):
126 dirname = os.path.basename(root)
127 if dirname.startswith(parentdir_prefix):
128 return {"version": dirname[len(parentdir_prefix):],
129 "full-revisionid": None,
130 "dirty": False, "error": None, "date": None}
131 rootdirs.append(root)
132 root = os.path.dirname(root) # up a level
133
134 if verbose:
135 print("Tried directories %s but none started with prefix %s" %
136 (str(rootdirs), parentdir_prefix))
137 raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
138
139
140 @register_vcs_handler("git", "get_keywords")
141 def git_get_keywords(versionfile_abs):
142 """Extract version information from the given file."""
143 # the code embedded in _version.py can just fetch the value of these
144 # keywords. When used from setup.py, we don't want to import _version.py,
145 # so we do it with a regexp instead. This function is not used from
146 # _version.py.
147 keywords = {}
148 try:
149 with open(versionfile_abs, "r") as fobj:
150 for line in fobj:
151 if line.strip().startswith("git_refnames ="):
152 mo = re.search(r'=\s*"(.*)"', line)
153 if mo:
154 keywords["refnames"] = mo.group(1)
155 if line.strip().startswith("git_full ="):
156 mo = re.search(r'=\s*"(.*)"', line)
157 if mo:
158 keywords["full"] = mo.group(1)
159 if line.strip().startswith("git_date ="):
160 mo = re.search(r'=\s*"(.*)"', line)
161 if mo:
162 keywords["date"] = mo.group(1)
163 except OSError:
164 pass
165 return keywords
166
167
168 @register_vcs_handler("git", "keywords")
169 def git_versions_from_keywords(keywords, tag_prefix, verbose):
170 """Get version information from git keywords."""
171 if "refnames" not in keywords:
172 raise NotThisMethod("Short version file found")
173 date = keywords.get("date")
174 if date is not None:
175 # Use only the last line. Previous lines may contain GPG signature
176 # information.
177 date = date.splitlines()[-1]
178
179 # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
180 # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
181 # -like" string, which we must then edit to make compliant), because
182 # it's been around since git-1.5.3, and it's too difficult to
183 # discover which version we're using, or to work around using an
184 # older one.
185 date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
186 refnames = keywords["refnames"].strip()
187 if refnames.startswith("$Format"):
188 if verbose:
189 print("keywords are unexpanded, not using")
190 raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
191 refs = {r.strip() for r in refnames.strip("()").split(",")}
192 # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
193 # just "foo-1.0". If we see a "tag: " prefix, prefer those.
194 TAG = "tag: "
195 tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
196 if not tags:
197 # Either we're using git < 1.8.3, or there really are no tags. We use
198 # a heuristic: assume all version tags have a digit. The old git %d
199 # expansion behaves like git log --decorate=short and strips out the
200 # refs/heads/ and refs/tags/ prefixes that would let us distinguish
201 # between branches and tags. By ignoring refnames without digits, we
202 # filter out many common branch names like "release" and
203 # "stabilization", as well as "HEAD" and "master".
204 tags = {r for r in refs if re.search(r'\d', r)}
205 if verbose:
206 print("discarding '%s', no digits" % ",".join(refs - tags))
207 if verbose:
208 print("likely tags: %s" % ",".join(sorted(tags)))
209 for ref in sorted(tags):
210 # sorting will prefer e.g. "2.0" over "2.0rc1"
211 if ref.startswith(tag_prefix):
212 r = ref[len(tag_prefix):]
213 # Filter out refs that exactly match prefix or that don't start
214 # with a number once the prefix is stripped (mostly a concern
215 # when prefix is '')
216 if not re.match(r'\d', r):
217 continue
218 if verbose:
219 print("picking %s" % r)
220 return {"version": r,
221 "full-revisionid": keywords["full"].strip(),
222 "dirty": False, "error": None,
223 "date": date}
224 # no suitable tags, so version is "0+unknown", but full hex is still there
225 if verbose:
226 print("no suitable tags, using unknown + full revision id")
227 return {"version": "0+unknown",
228 "full-revisionid": keywords["full"].strip(),
229 "dirty": False, "error": "no suitable tags", "date": None}
230
231
232 @register_vcs_handler("git", "pieces_from_vcs")
233 def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
234 """Get version from 'git describe' in the root of the source tree.
235
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.
239 """
240 GITS = ["git"]
241 if sys.platform == "win32":
242 GITS = ["git.cmd", "git.exe"]
243
244 # GIT_DIR can interfere with correct operation of Versioneer.
245 # It may be intended to be passed to the Versioneer-versioned project,
246 # but that should not change where we get our version from.
247 env = os.environ.copy()
248 env.pop("GIT_DIR", None)
249 runner = functools.partial(runner, env=env)
250
251 _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root,
252 hide_stderr=not verbose)
253 if rc != 0:
254 if verbose:
255 print("Directory %s not under git control" % root)
256 raise NotThisMethod("'git rev-parse --git-dir' returned error")
257
258 # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
259 # if there isn't one, this yields HEX[-dirty] (no NUM)
260 describe_out, rc = runner(GITS, [
261 "describe", "--tags", "--dirty", "--always", "--long",
262 "--match", f"{tag_prefix}[[:digit:]]*"
263 ], cwd=root)
264 # --long was added in git-1.5.5
265 if describe_out is None:
266 raise NotThisMethod("'git describe' failed")
267 describe_out = describe_out.strip()
268 full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
269 if full_out is None:
270 raise NotThisMethod("'git rev-parse' failed")
271 full_out = full_out.strip()
272
273 pieces = {}
274 pieces["long"] = full_out
275 pieces["short"] = full_out[:7] # maybe improved later
276 pieces["error"] = None
277
278 branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
279 cwd=root)
280 # --abbrev-ref was added in git-1.6.3
281 if rc != 0 or branch_name is None:
282 raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
283 branch_name = branch_name.strip()
284
285 if branch_name == "HEAD":
286 # If we aren't exactly on a branch, pick a branch which represents
287 # the current commit. If all else fails, we are on a branchless
288 # commit.
289 branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
290 # --contains was added in git-1.5.4
291 if rc != 0 or branches is None:
292 raise NotThisMethod("'git branch --contains' returned error")
293 branches = branches.split("\n")
294
295 # Remove the first line if we're running detached
296 if "(" in branches[0]:
297 branches.pop(0)
298
299 # Strip off the leading "* " from the list of branches.
300 branches = [branch[2:] for branch in branches]
301 if "master" in branches:
302 branch_name = "master"
303 elif not branches:
304 branch_name = None
305 else:
306 # Pick the first branch that is returned. Good or bad.
307 branch_name = branches[0]
308
309 pieces["branch"] = branch_name
310
311 # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
312 # TAG might have hyphens.
313 git_describe = describe_out
314
315 # look for -dirty suffix
316 dirty = git_describe.endswith("-dirty")
317 pieces["dirty"] = dirty
318 if dirty:
319 git_describe = git_describe[:git_describe.rindex("-dirty")]
320
321 # now we have TAG-NUM-gHEX or HEX
322
323 if "-" in git_describe:
324 # TAG-NUM-gHEX
325 mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
326 if not mo:
327 # unparsable. Maybe git-describe is misbehaving?
328 pieces["error"] = ("unable to parse git-describe output: '%s'"
329 % describe_out)
330 return pieces
331
332 # tag
333 full_tag = mo.group(1)
334 if not full_tag.startswith(tag_prefix):
335 if verbose:
336 fmt = "tag '%s' doesn't start with prefix '%s'"
337 print(fmt % (full_tag, tag_prefix))
338 pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
339 % (full_tag, tag_prefix))
340 return pieces
341 pieces["closest-tag"] = full_tag[len(tag_prefix):]
342
343 # distance: number of commits since tag
344 pieces["distance"] = int(mo.group(2))
345
346 # commit: short hex revision ID
347 pieces["short"] = mo.group(3)
348
349 else:
350 # HEX: no tags
351 pieces["closest-tag"] = None
352 out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
353 pieces["distance"] = len(out.split()) # total number of commits
354
355 # commit date: see ISO-8601 comment in git_versions_from_keywords()
356 date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip()
357 # Use only the last line. Previous lines may contain GPG signature
358 # information.
359 date = date.splitlines()[-1]
360 pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
361
362 return pieces
363
364
365 def plus_or_dot(pieces):
366 """Return a + if we don't already have one, else return a ."""
367 if "+" in pieces.get("closest-tag", ""):
368 return "."
369 return "+"
370
371
372 def render_pep440(pieces):
373 """Build up version string, with post-release "local version identifier".
374
375 Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
376 get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
377
378 Exceptions:
379 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
380 """
381 if pieces["closest-tag"]:
382 rendered = pieces["closest-tag"]
383 if pieces["distance"] or pieces["dirty"]:
384 rendered += plus_or_dot(pieces)
385 rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
386 if pieces["dirty"]:
387 rendered += ".dirty"
388 else:
389 # exception #1
390 rendered = "0+untagged.%d.g%s" % (pieces["distance"],
391 pieces["short"])
392 if pieces["dirty"]:
393 rendered += ".dirty"
394 return rendered
395
396
397 def render_pep440_branch(pieces):
398 """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
399
400 The ".dev0" means not master branch. Note that .dev0 sorts backwards
401 (a feature branch will appear "older" than the master branch).
402
403 Exceptions:
404 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
405 """
406 if pieces["closest-tag"]:
407 rendered = pieces["closest-tag"]
408 if pieces["distance"] or pieces["dirty"]:
409 if pieces["branch"] != "master":
410 rendered += ".dev0"
411 rendered += plus_or_dot(pieces)
412 rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
413 if pieces["dirty"]:
414 rendered += ".dirty"
415 else:
416 # exception #1
417 rendered = "0"
418 if pieces["branch"] != "master":
419 rendered += ".dev0"
420 rendered += "+untagged.%d.g%s" % (pieces["distance"],
421 pieces["short"])
422 if pieces["dirty"]:
423 rendered += ".dirty"
424 return rendered
425
426
427 def pep440_split_post(ver):
428 """Split pep440 version string at the post-release segment.
429
430 Returns the release segments before the post-release and the
431 post-release version number (or -1 if no post-release segment is present).
432 """
433 vc = str.split(ver, ".post")
434 return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
435
436
437 def render_pep440_pre(pieces):
438 """TAG[.postN.devDISTANCE] -- No -dirty.
439
440 Exceptions:
441 1: no tags. 0.post0.devDISTANCE
442 """
443 if pieces["closest-tag"]:
444 if pieces["distance"]:
445 # update the post release segment
446 tag_version, post_version = pep440_split_post(pieces["closest-tag"])
447 rendered = tag_version
448 if post_version is not None:
449 rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"])
450 else:
451 rendered += ".post0.dev%d" % (pieces["distance"])
452 else:
453 # no commits, use the tag as the version
454 rendered = pieces["closest-tag"]
455 else:
456 # exception #1
457 rendered = "0.post0.dev%d" % pieces["distance"]
458 return rendered
459
460
461 def render_pep440_post(pieces):
462 """TAG[.postDISTANCE[.dev0]+gHEX] .
463
464 The ".dev0" means dirty. Note that .dev0 sorts backwards
465 (a dirty tree will appear "older" than the corresponding clean one),
466 but you shouldn't be releasing software with -dirty anyways.
467
468 Exceptions:
469 1: no tags. 0.postDISTANCE[.dev0]
470 """
471 if pieces["closest-tag"]:
472 rendered = pieces["closest-tag"]
473 if pieces["distance"] or pieces["dirty"]:
474 rendered += ".post%d" % pieces["distance"]
475 if pieces["dirty"]:
476 rendered += ".dev0"
477 rendered += plus_or_dot(pieces)
478 rendered += "g%s" % pieces["short"]
479 else:
480 # exception #1
481 rendered = "0.post%d" % pieces["distance"]
482 if pieces["dirty"]:
483 rendered += ".dev0"
484 rendered += "+g%s" % pieces["short"]
485 return rendered
486
487
488 def render_pep440_post_branch(pieces):
489 """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
490
491 The ".dev0" means not master branch.
492
493 Exceptions:
494 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
495 """
496 if pieces["closest-tag"]:
497 rendered = pieces["closest-tag"]
498 if pieces["distance"] or pieces["dirty"]:
499 rendered += ".post%d" % pieces["distance"]
500 if pieces["branch"] != "master":
501 rendered += ".dev0"
502 rendered += plus_or_dot(pieces)
503 rendered += "g%s" % pieces["short"]
504 if pieces["dirty"]:
505 rendered += ".dirty"
506 else:
507 # exception #1
508 rendered = "0.post%d" % pieces["distance"]
509 if pieces["branch"] != "master":
510 rendered += ".dev0"
511 rendered += "+g%s" % pieces["short"]
512 if pieces["dirty"]:
513 rendered += ".dirty"
514 return rendered
515
516
517 def render_pep440_old(pieces):
518 """TAG[.postDISTANCE[.dev0]] .
519
520 The ".dev0" means dirty.
521
522 Exceptions:
523 1: no tags. 0.postDISTANCE[.dev0]
524 """
525 if pieces["closest-tag"]:
526 rendered = pieces["closest-tag"]
527 if pieces["distance"] or pieces["dirty"]:
528 rendered += ".post%d" % pieces["distance"]
529 if pieces["dirty"]:
530 rendered += ".dev0"
531 else:
532 # exception #1
533 rendered = "0.post%d" % pieces["distance"]
534 if pieces["dirty"]:
535 rendered += ".dev0"
536 return rendered
537
538
539 def render_git_describe(pieces):
540 """TAG[-DISTANCE-gHEX][-dirty].
541
542 Like 'git describe --tags --dirty --always'.
543
544 Exceptions:
545 1: no tags. HEX[-dirty] (note: no 'g' prefix)
546 """
547 if pieces["closest-tag"]:
548 rendered = pieces["closest-tag"]
549 if pieces["distance"]:
550 rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
551 else:
552 # exception #1
553 rendered = pieces["short"]
554 if pieces["dirty"]:
555 rendered += "-dirty"
556 return rendered
557
558
559 def render_git_describe_long(pieces):
560 """TAG-DISTANCE-gHEX[-dirty].
561
562 Like 'git describe --tags --dirty --always -long'.
563 The distance/hash is unconditional.
564
565 Exceptions:
566 1: no tags. HEX[-dirty] (note: no 'g' prefix)
567 """
568 if pieces["closest-tag"]:
569 rendered = pieces["closest-tag"]
570 rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
571 else:
572 # exception #1
573 rendered = pieces["short"]
574 if pieces["dirty"]:
575 rendered += "-dirty"
576 return rendered
577
578
579 def render(pieces, style):
580 """Render the given version pieces into the requested style."""
581 if pieces["error"]:
582 return {"version": "unknown",
583 "full-revisionid": pieces.get("long"),
584 "dirty": None,
585 "error": pieces["error"],
586 "date": None}
587
588 if not style or style == "default":
589 style = "pep440" # the default
590
591 if style == "pep440":
592 rendered = render_pep440(pieces)
593 elif style == "pep440-branch":
594 rendered = render_pep440_branch(pieces)
595 elif style == "pep440-pre":
596 rendered = render_pep440_pre(pieces)
597 elif style == "pep440-post":
598 rendered = render_pep440_post(pieces)
599 elif style == "pep440-post-branch":
600 rendered = render_pep440_post_branch(pieces)
601 elif style == "pep440-old":
602 rendered = render_pep440_old(pieces)
603 elif style == "git-describe":
604 rendered = render_git_describe(pieces)
605 elif style == "git-describe-long":
606 rendered = render_git_describe_long(pieces)
607 else:
608 raise ValueError("unknown style '%s'" % style)
609
610 return {"version": rendered, "full-revisionid": pieces["long"],
611 "dirty": pieces["dirty"], "error": None,
612 "date": pieces.get("date")}
613
614
615 def get_versions():
616 """Get version information or return default if unable to do so."""
617 # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
618 # __file__, we can work backwards from there to the root. Some
619 # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
620 # case we can only use expanded keywords.
621
622 cfg = get_config()
623 verbose = cfg.verbose
624
625 try:
626 return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
627 verbose)
628 except NotThisMethod:
629 pass
630
631 try:
632 root = os.path.realpath(__file__)
633 # versionfile_source is the relative path from the top of the source
634 # tree (where the .git directory might live) to this file. Invert
635 # this to find the root from __file__.
636 for _ in cfg.versionfile_source.split('/'):
637 root = os.path.dirname(root)
638 except NameError:
639 return {"version": "0+unknown", "full-revisionid": None,
640 "dirty": None,
641 "error": "unable to find root of source tree",
642 "date": None}
643
644 try:
645 pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
646 return render(pieces, cfg.style)
647 except NotThisMethod:
648 pass
649
650 try:
651 if cfg.parentdir_prefix:
652 return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
653 except NotThisMethod:
654 pass
655
656 return {"version": "0+unknown", "full-revisionid": None,
657 "dirty": None,
658 "error": "unable to compute version", "date": None}