1+
12# This file helps to compute a version number in source trees obtained from
23# git-archive tarball (such as those provided by githubs download-from-tag
34# feature). Distribution tarballs (built by setup.py sdist) and build
1112"""Git implementation of _version.py."""
1213
1314import errno
14- import functools
1515import os
1616import re
1717import subprocess
1818import sys
1919from typing import Any , Callable , Dict , List , Optional , Tuple
20+ import functools
2021
2122
2223def get_keywords () -> Dict [str , str ]:
@@ -67,14 +68,12 @@ class NotThisMethod(Exception):
6768
6869def register_vcs_handler (vcs : str , method : str ) -> Callable : # decorator
6970 """Create decorator to mark a method as the handler of a VCS."""
70-
7171 def decorate (f : Callable ) -> Callable :
7272 """Store f in HANDLERS[vcs][method]."""
7373 if vcs not in HANDLERS :
7474 HANDLERS [vcs ] = {}
7575 HANDLERS [vcs ][method ] = f
7676 return f
77-
7877 return decorate
7978
8079
@@ -101,14 +100,10 @@ def run_command(
101100 try :
102101 dispcmd = str ([command ] + args )
103102 # 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- )
103+ process = subprocess .Popen ([command ] + args , cwd = cwd , env = env ,
104+ stdout = subprocess .PIPE ,
105+ stderr = (subprocess .PIPE if hide_stderr
106+ else None ), ** popen_kwargs )
112107 break
113108 except OSError as e :
114109 if e .errno == errno .ENOENT :
@@ -146,21 +141,15 @@ def versions_from_parentdir(
146141 for _ in range (3 ):
147142 dirname = os .path .basename (root )
148143 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- }
144+ return {"version" : dirname [len (parentdir_prefix ):],
145+ "full-revisionid" : None ,
146+ "dirty" : False , "error" : None , "date" : None }
156147 rootdirs .append (root )
157148 root = os .path .dirname (root ) # up a level
158149
159150 if verbose :
160- print (
161- "Tried directories %s but none started with prefix %s"
162- % (str (rootdirs ), parentdir_prefix )
163- )
151+ print ("Tried directories %s but none started with prefix %s" %
152+ (str (rootdirs ), parentdir_prefix ))
164153 raise NotThisMethod ("rootdir doesn't start with parentdir_prefix" )
165154
166155
@@ -223,7 +212,7 @@ def git_versions_from_keywords(
223212 # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
224213 # just "foo-1.0". If we see a "tag: " prefix, prefer those.
225214 TAG = "tag: "
226- tags = {r [len (TAG ) :] for r in refs if r .startswith (TAG )}
215+ tags = {r [len (TAG ):] for r in refs if r .startswith (TAG )}
227216 if not tags :
228217 # Either we're using git < 1.8.3, or there really are no tags. We use
229218 # a heuristic: assume all version tags have a digit. The old git %d
@@ -232,44 +221,40 @@ def git_versions_from_keywords(
232221 # between branches and tags. By ignoring refnames without digits, we
233222 # filter out many common branch names like "release" and
234223 # "stabilization", as well as "HEAD" and "master".
235- tags = {r for r in refs if re .search (r"\d" , r )}
224+ tags = {r for r in refs if re .search (r'\d' , r )}
236225 if verbose :
237226 print ("discarding '%s', no digits" % "," .join (refs - tags ))
238227 if verbose :
239228 print ("likely tags: %s" % "," .join (sorted (tags )))
240229 for ref in sorted (tags ):
241230 # sorting will prefer e.g. "2.0" over "2.0rc1"
242231 if ref .startswith (tag_prefix ):
243- r = ref [len (tag_prefix ) :]
232+ r = ref [len (tag_prefix ):]
244233 # Filter out refs that exactly match prefix or that don't start
245234 # with a number once the prefix is stripped (mostly a concern
246235 # when prefix is '')
247- if not re .match (r"\d" , r ):
236+ if not re .match (r'\d' , r ):
248237 continue
249238 if verbose :
250239 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- }
240+ return {"version" : r ,
241+ "full-revisionid" : keywords ["full" ].strip (),
242+ "dirty" : False , "error" : None ,
243+ "date" : date }
258244 # no suitable tags, so version is "0+unknown", but full hex is still there
259245 if verbose :
260246 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- }
247+ return {"version" : "0+unknown" ,
248+ "full-revisionid" : keywords ["full" ].strip (),
249+ "dirty" : False , "error" : "no suitable tags" , "date" : None }
268250
269251
270252@register_vcs_handler ("git" , "pieces_from_vcs" )
271253def git_pieces_from_vcs (
272- tag_prefix : str , root : str , verbose : bool , runner : Callable = run_command
254+ tag_prefix : str ,
255+ root : str ,
256+ verbose : bool ,
257+ runner : Callable = run_command
273258) -> Dict [str , Any ]:
274259 """Get version from 'git describe' in the root of the source tree.
275260
@@ -288,27 +273,19 @@ def git_pieces_from_vcs(
288273 env .pop ("GIT_DIR" , None )
289274 runner = functools .partial (runner , env = env )
290275
291- _ , rc = runner (GITS , ["rev-parse" , "--git-dir" ], cwd = root , hide_stderr = not verbose )
276+ _ , rc = runner (GITS , ["rev-parse" , "--git-dir" ], cwd = root ,
277+ hide_stderr = not verbose )
292278 if rc != 0 :
293279 if verbose :
294280 print ("Directory %s not under git control" % root )
295281 raise NotThisMethod ("'git rev-parse --git-dir' returned error" )
296282
297283 # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
298284 # if there isn't one, this yields HEX[-dirty] (no NUM)
299- describe_out , rc = runner (
300- GITS ,
301- [
302- "describe" ,
303- "--tags" ,
304- "--dirty" ,
305- "--always" ,
306- "--long" ,
307- "--match" ,
308- f"{ tag_prefix } [[:digit:]]*" ,
309- ],
310- cwd = root ,
311- )
285+ describe_out , rc = runner (GITS , [
286+ "describe" , "--tags" , "--dirty" , "--always" , "--long" ,
287+ "--match" , f"{ tag_prefix } [[:digit:]]*"
288+ ], cwd = root )
312289 # --long was added in git-1.5.5
313290 if describe_out is None :
314291 raise NotThisMethod ("'git describe' failed" )
@@ -323,7 +300,8 @@ def git_pieces_from_vcs(
323300 pieces ["short" ] = full_out [:7 ] # maybe improved later
324301 pieces ["error" ] = None
325302
326- branch_name , rc = runner (GITS , ["rev-parse" , "--abbrev-ref" , "HEAD" ], cwd = root )
303+ branch_name , rc = runner (GITS , ["rev-parse" , "--abbrev-ref" , "HEAD" ],
304+ cwd = root )
327305 # --abbrev-ref was added in git-1.6.3
328306 if rc != 0 or branch_name is None :
329307 raise NotThisMethod ("'git rev-parse --abbrev-ref' returned error" )
@@ -363,16 +341,17 @@ def git_pieces_from_vcs(
363341 dirty = git_describe .endswith ("-dirty" )
364342 pieces ["dirty" ] = dirty
365343 if dirty :
366- git_describe = git_describe [: git_describe .rindex ("-dirty" )]
344+ git_describe = git_describe [:git_describe .rindex ("-dirty" )]
367345
368346 # now we have TAG-NUM-gHEX or HEX
369347
370348 if "-" in git_describe :
371349 # TAG-NUM-gHEX
372- mo = re .search (r" ^(.+)-(\d+)-g([0-9a-f]+)$" , git_describe )
350+ mo = re .search (r' ^(.+)-(\d+)-g([0-9a-f]+)$' , git_describe )
373351 if not mo :
374352 # unparsable. Maybe git-describe is misbehaving?
375- pieces ["error" ] = "unable to parse git-describe output: '%s'" % describe_out
353+ pieces ["error" ] = ("unable to parse git-describe output: '%s'"
354+ % describe_out )
376355 return pieces
377356
378357 # tag
@@ -381,12 +360,10 @@ def git_pieces_from_vcs(
381360 if verbose :
382361 fmt = "tag '%s' doesn't start with prefix '%s'"
383362 print (fmt % (full_tag , tag_prefix ))
384- pieces ["error" ] = "tag '%s' doesn't start with prefix '%s'" % (
385- full_tag ,
386- tag_prefix ,
387- )
363+ pieces ["error" ] = ("tag '%s' doesn't start with prefix '%s'"
364+ % (full_tag , tag_prefix ))
388365 return pieces
389- pieces ["closest-tag" ] = full_tag [len (tag_prefix ) :]
366+ pieces ["closest-tag" ] = full_tag [len (tag_prefix ):]
390367
391368 # distance: number of commits since tag
392369 pieces ["distance" ] = int (mo .group (2 ))
@@ -435,7 +412,8 @@ def render_pep440(pieces: Dict[str, Any]) -> str:
435412 rendered += ".dirty"
436413 else :
437414 # exception #1
438- rendered = "0+untagged.%d.g%s" % (pieces ["distance" ], pieces ["short" ])
415+ rendered = "0+untagged.%d.g%s" % (pieces ["distance" ],
416+ pieces ["short" ])
439417 if pieces ["dirty" ]:
440418 rendered += ".dirty"
441419 return rendered
@@ -464,7 +442,8 @@ def render_pep440_branch(pieces: Dict[str, Any]) -> str:
464442 rendered = "0"
465443 if pieces ["branch" ] != "master" :
466444 rendered += ".dev0"
467- rendered += "+untagged.%d.g%s" % (pieces ["distance" ], pieces ["short" ])
445+ rendered += "+untagged.%d.g%s" % (pieces ["distance" ],
446+ pieces ["short" ])
468447 if pieces ["dirty" ]:
469448 rendered += ".dirty"
470449 return rendered
@@ -625,13 +604,11 @@ def render_git_describe_long(pieces: Dict[str, Any]) -> str:
625604def render (pieces : Dict [str , Any ], style : str ) -> Dict [str , Any ]:
626605 """Render the given version pieces into the requested style."""
627606 if pieces ["error" ]:
628- return {
629- "version" : "unknown" ,
630- "full-revisionid" : pieces .get ("long" ),
631- "dirty" : None ,
632- "error" : pieces ["error" ],
633- "date" : None ,
634- }
607+ return {"version" : "unknown" ,
608+ "full-revisionid" : pieces .get ("long" ),
609+ "dirty" : None ,
610+ "error" : pieces ["error" ],
611+ "date" : None }
635612
636613 if not style or style == "default" :
637614 style = "pep440" # the default
@@ -655,13 +632,9 @@ def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
655632 else :
656633 raise ValueError ("unknown style '%s'" % style )
657634
658- return {
659- "version" : rendered ,
660- "full-revisionid" : pieces ["long" ],
661- "dirty" : pieces ["dirty" ],
662- "error" : None ,
663- "date" : pieces .get ("date" ),
664- }
635+ return {"version" : rendered , "full-revisionid" : pieces ["long" ],
636+ "dirty" : pieces ["dirty" ], "error" : None ,
637+ "date" : pieces .get ("date" )}
665638
666639
667640def get_versions () -> Dict [str , Any ]:
@@ -675,7 +648,8 @@ def get_versions() -> Dict[str, Any]:
675648 verbose = cfg .verbose
676649
677650 try :
678- return git_versions_from_keywords (get_keywords (), cfg .tag_prefix , verbose )
651+ return git_versions_from_keywords (get_keywords (), cfg .tag_prefix ,
652+ verbose )
679653 except NotThisMethod :
680654 pass
681655
@@ -684,16 +658,13 @@ def get_versions() -> Dict[str, Any]:
684658 # versionfile_source is the relative path from the top of the source
685659 # tree (where the .git directory might live) to this file. Invert
686660 # this to find the root from __file__.
687- for _ in cfg .versionfile_source .split ("/" ):
661+ for _ in cfg .versionfile_source .split ('/' ):
688662 root = os .path .dirname (root )
689663 except NameError :
690- return {
691- "version" : "0+unknown" ,
692- "full-revisionid" : None ,
693- "dirty" : None ,
694- "error" : "unable to find root of source tree" ,
695- "date" : None ,
696- }
664+ return {"version" : "0+unknown" , "full-revisionid" : None ,
665+ "dirty" : None ,
666+ "error" : "unable to find root of source tree" ,
667+ "date" : None }
697668
698669 try :
699670 pieces = git_pieces_from_vcs (cfg .tag_prefix , root , verbose )
@@ -707,10 +678,6 @@ def get_versions() -> Dict[str, Any]:
707678 except NotThisMethod :
708679 pass
709680
710- return {
711- "version" : "0+unknown" ,
712- "full-revisionid" : None ,
713- "dirty" : None ,
714- "error" : "unable to compute version" ,
715- "date" : None ,
716- }
681+ return {"version" : "0+unknown" , "full-revisionid" : None ,
682+ "dirty" : None ,
683+ "error" : "unable to compute version" , "date" : None }
0 commit comments