1-
21# This file helps to compute a version number in source trees obtained from
32# git-archive tarball (such as those provided by githubs download-from-tag
43# feature). Distribution tarballs (built by setup.py sdist) and build
1211"""Git implementation of _version.py."""
1312
1413import errno
14+ import functools
1515import os
1616import re
1717import subprocess
1818import sys
1919from typing import Callable , Dict
20- import functools
2120
2221
2322def get_keywords ():
@@ -61,17 +60,18 @@ class NotThisMethod(Exception):
6160
6261def register_vcs_handler (vcs , method ): # decorator
6362 """Create decorator to mark a method as the handler of a VCS."""
63+
6464 def decorate (f ):
6565 """Store f in HANDLERS[vcs][method]."""
6666 if vcs not in HANDLERS :
6767 HANDLERS [vcs ] = {}
6868 HANDLERS [vcs ][method ] = f
6969 return f
70+
7071 return decorate
7172
7273
73- def run_command (commands , args , cwd = None , verbose = False , hide_stderr = False ,
74- env = None ):
74+ def run_command (commands , args , cwd = None , verbose = False , hide_stderr = False , env = None ):
7575 """Call the given command(s)."""
7676 assert isinstance (commands , list )
7777 process = None
@@ -87,10 +87,14 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
8787 try :
8888 dispcmd = str ([command ] + args )
8989 # 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 )
90+ process = subprocess .Popen (
91+ [command ] + args ,
92+ cwd = cwd ,
93+ env = env ,
94+ stdout = subprocess .PIPE ,
95+ stderr = (subprocess .PIPE if hide_stderr else None ),
96+ ** popen_kwargs ,
97+ )
9498 break
9599 except OSError :
96100 e = sys .exc_info ()[1 ]
@@ -125,15 +129,21 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
125129 for _ in range (3 ):
126130 dirname = os .path .basename (root )
127131 if dirname .startswith (parentdir_prefix ):
128- return {"version" : dirname [len (parentdir_prefix ):],
129- "full-revisionid" : None ,
130- "dirty" : False , "error" : None , "date" : None }
132+ return {
133+ "version" : dirname [len (parentdir_prefix ) :],
134+ "full-revisionid" : None ,
135+ "dirty" : False ,
136+ "error" : None ,
137+ "date" : None ,
138+ }
131139 rootdirs .append (root )
132140 root = os .path .dirname (root ) # up a level
133141
134142 if verbose :
135- print ("Tried directories %s but none started with prefix %s" %
136- (str (rootdirs ), parentdir_prefix ))
143+ print (
144+ "Tried directories %s but none started with prefix %s"
145+ % (str (rootdirs ), parentdir_prefix )
146+ )
137147 raise NotThisMethod ("rootdir doesn't start with parentdir_prefix" )
138148
139149
@@ -192,7 +202,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
192202 # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
193203 # just "foo-1.0". If we see a "tag: " prefix, prefer those.
194204 TAG = "tag: "
195- tags = {r [len (TAG ):] for r in refs if r .startswith (TAG )}
205+ tags = {r [len (TAG ) :] for r in refs if r .startswith (TAG )}
196206 if not tags :
197207 # Either we're using git < 1.8.3, or there really are no tags. We use
198208 # a heuristic: assume all version tags have a digit. The old git %d
@@ -201,32 +211,39 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
201211 # between branches and tags. By ignoring refnames without digits, we
202212 # filter out many common branch names like "release" and
203213 # "stabilization", as well as "HEAD" and "master".
204- tags = {r for r in refs if re .search (r'\d' , r )}
214+ tags = {r for r in refs if re .search (r"\d" , r )}
205215 if verbose :
206216 print ("discarding '%s', no digits" % "," .join (refs - tags ))
207217 if verbose :
208218 print ("likely tags: %s" % "," .join (sorted (tags )))
209219 for ref in sorted (tags ):
210220 # sorting will prefer e.g. "2.0" over "2.0rc1"
211221 if ref .startswith (tag_prefix ):
212- r = ref [len (tag_prefix ):]
222+ r = ref [len (tag_prefix ) :]
213223 # Filter out refs that exactly match prefix or that don't start
214224 # with a number once the prefix is stripped (mostly a concern
215225 # when prefix is '')
216- if not re .match (r'\d' , r ):
226+ if not re .match (r"\d" , r ):
217227 continue
218228 if verbose :
219229 print ("picking %s" % r )
220- return {"version" : r ,
221- "full-revisionid" : keywords ["full" ].strip (),
222- "dirty" : False , "error" : None ,
223- "date" : date }
230+ return {
231+ "version" : r ,
232+ "full-revisionid" : keywords ["full" ].strip (),
233+ "dirty" : False ,
234+ "error" : None ,
235+ "date" : date ,
236+ }
224237 # no suitable tags, so version is "0+unknown", but full hex is still there
225238 if verbose :
226239 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 }
240+ return {
241+ "version" : "0+unknown" ,
242+ "full-revisionid" : keywords ["full" ].strip (),
243+ "dirty" : False ,
244+ "error" : "no suitable tags" ,
245+ "date" : None ,
246+ }
230247
231248
232249@register_vcs_handler ("git" , "pieces_from_vcs" )
@@ -248,19 +265,27 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
248265 env .pop ("GIT_DIR" , None )
249266 runner = functools .partial (runner , env = env )
250267
251- _ , rc = runner (GITS , ["rev-parse" , "--git-dir" ], cwd = root ,
252- hide_stderr = not verbose )
268+ _ , rc = runner (GITS , ["rev-parse" , "--git-dir" ], cwd = root , hide_stderr = not verbose )
253269 if rc != 0 :
254270 if verbose :
255271 print ("Directory %s not under git control" % root )
256272 raise NotThisMethod ("'git rev-parse --git-dir' returned error" )
257273
258274 # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
259275 # 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 )
276+ describe_out , rc = runner (
277+ GITS ,
278+ [
279+ "describe" ,
280+ "--tags" ,
281+ "--dirty" ,
282+ "--always" ,
283+ "--long" ,
284+ "--match" ,
285+ f"{ tag_prefix } [[:digit:]]*" ,
286+ ],
287+ cwd = root ,
288+ )
264289 # --long was added in git-1.5.5
265290 if describe_out is None :
266291 raise NotThisMethod ("'git describe' failed" )
@@ -275,8 +300,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
275300 pieces ["short" ] = full_out [:7 ] # maybe improved later
276301 pieces ["error" ] = None
277302
278- branch_name , rc = runner (GITS , ["rev-parse" , "--abbrev-ref" , "HEAD" ],
279- cwd = root )
303+ branch_name , rc = runner (GITS , ["rev-parse" , "--abbrev-ref" , "HEAD" ], cwd = root )
280304 # --abbrev-ref was added in git-1.6.3
281305 if rc != 0 or branch_name is None :
282306 raise NotThisMethod ("'git rev-parse --abbrev-ref' returned error" )
@@ -316,17 +340,16 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
316340 dirty = git_describe .endswith ("-dirty" )
317341 pieces ["dirty" ] = dirty
318342 if dirty :
319- git_describe = git_describe [:git_describe .rindex ("-dirty" )]
343+ git_describe = git_describe [: git_describe .rindex ("-dirty" )]
320344
321345 # now we have TAG-NUM-gHEX or HEX
322346
323347 if "-" in git_describe :
324348 # TAG-NUM-gHEX
325- mo = re .search (r' ^(.+)-(\d+)-g([0-9a-f]+)$' , git_describe )
349+ mo = re .search (r" ^(.+)-(\d+)-g([0-9a-f]+)$" , git_describe )
326350 if not mo :
327351 # unparsable. Maybe git-describe is misbehaving?
328- pieces ["error" ] = ("unable to parse git-describe output: '%s'"
329- % describe_out )
352+ pieces ["error" ] = "unable to parse git-describe output: '%s'" % describe_out
330353 return pieces
331354
332355 # tag
@@ -335,10 +358,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
335358 if verbose :
336359 fmt = "tag '%s' doesn't start with prefix '%s'"
337360 print (fmt % (full_tag , tag_prefix ))
338- pieces ["error" ] = ("tag '%s' doesn't start with prefix '%s'"
339- % (full_tag , tag_prefix ))
361+ pieces ["error" ] = "tag '%s' doesn't start with prefix '%s'" % (
362+ full_tag ,
363+ tag_prefix ,
364+ )
340365 return pieces
341- pieces ["closest-tag" ] = full_tag [len (tag_prefix ):]
366+ pieces ["closest-tag" ] = full_tag [len (tag_prefix ) :]
342367
343368 # distance: number of commits since tag
344369 pieces ["distance" ] = int (mo .group (2 ))
@@ -387,8 +412,7 @@ def render_pep440(pieces):
387412 rendered += ".dirty"
388413 else :
389414 # exception #1
390- rendered = "0+untagged.%d.g%s" % (pieces ["distance" ],
391- pieces ["short" ])
415+ rendered = "0+untagged.%d.g%s" % (pieces ["distance" ], pieces ["short" ])
392416 if pieces ["dirty" ]:
393417 rendered += ".dirty"
394418 return rendered
@@ -417,8 +441,7 @@ def render_pep440_branch(pieces):
417441 rendered = "0"
418442 if pieces ["branch" ] != "master" :
419443 rendered += ".dev0"
420- rendered += "+untagged.%d.g%s" % (pieces ["distance" ],
421- pieces ["short" ])
444+ rendered += "+untagged.%d.g%s" % (pieces ["distance" ], pieces ["short" ])
422445 if pieces ["dirty" ]:
423446 rendered += ".dirty"
424447 return rendered
@@ -579,11 +602,13 @@ def render_git_describe_long(pieces):
579602def render (pieces , style ):
580603 """Render the given version pieces into the requested style."""
581604 if pieces ["error" ]:
582- return {"version" : "unknown" ,
583- "full-revisionid" : pieces .get ("long" ),
584- "dirty" : None ,
585- "error" : pieces ["error" ],
586- "date" : None }
605+ return {
606+ "version" : "unknown" ,
607+ "full-revisionid" : pieces .get ("long" ),
608+ "dirty" : None ,
609+ "error" : pieces ["error" ],
610+ "date" : None ,
611+ }
587612
588613 if not style or style == "default" :
589614 style = "pep440" # the default
@@ -607,9 +632,13 @@ def render(pieces, style):
607632 else :
608633 raise ValueError ("unknown style '%s'" % style )
609634
610- return {"version" : rendered , "full-revisionid" : pieces ["long" ],
611- "dirty" : pieces ["dirty" ], "error" : None ,
612- "date" : pieces .get ("date" )}
635+ return {
636+ "version" : rendered ,
637+ "full-revisionid" : pieces ["long" ],
638+ "dirty" : pieces ["dirty" ],
639+ "error" : None ,
640+ "date" : pieces .get ("date" ),
641+ }
613642
614643
615644def get_versions ():
@@ -623,8 +652,7 @@ def get_versions():
623652 verbose = cfg .verbose
624653
625654 try :
626- return git_versions_from_keywords (get_keywords (), cfg .tag_prefix ,
627- verbose )
655+ return git_versions_from_keywords (get_keywords (), cfg .tag_prefix , verbose )
628656 except NotThisMethod :
629657 pass
630658
@@ -633,13 +661,16 @@ def get_versions():
633661 # versionfile_source is the relative path from the top of the source
634662 # tree (where the .git directory might live) to this file. Invert
635663 # this to find the root from __file__.
636- for _ in cfg .versionfile_source .split ('/' ):
664+ for _ in cfg .versionfile_source .split ("/" ):
637665 root = os .path .dirname (root )
638666 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 }
667+ return {
668+ "version" : "0+unknown" ,
669+ "full-revisionid" : None ,
670+ "dirty" : None ,
671+ "error" : "unable to find root of source tree" ,
672+ "date" : None ,
673+ }
643674
644675 try :
645676 pieces = git_pieces_from_vcs (cfg .tag_prefix , root , verbose )
@@ -653,6 +684,10 @@ def get_versions():
653684 except NotThisMethod :
654685 pass
655686
656- return {"version" : "0+unknown" , "full-revisionid" : None ,
657- "dirty" : None ,
658- "error" : "unable to compute version" , "date" : None }
687+ return {
688+ "version" : "0+unknown" ,
689+ "full-revisionid" : None ,
690+ "dirty" : None ,
691+ "error" : "unable to compute version" ,
692+ "date" : None ,
693+ }
0 commit comments