RecursiveNamespaceV2 0.0.1__py3-none-any.whl

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