11# vim: tabstop=4 shiftwidth=4 softtabstop=4
22
33# Copyright 2011 OpenStack LLC.
4+ # Copyright 2012-2013 Hewlett-Packard Development Company, L.P.
45# All Rights Reserved.
56#
67# Licensed under the Apache License, Version 2.0 (the "License"); you may
1920Utilities with minimum-depends for use in setup.py
2021"""
2122
22- import datetime
23+ import email
2324import os
2425import re
2526import subprocess
@@ -33,20 +34,21 @@ def parse_mailmap(mailmap='.mailmap'):
3334 if os .path .exists (mailmap ):
3435 with open (mailmap , 'r' ) as fp :
3536 for l in fp :
36- l = l .strip ()
37- if not l .startswith ('#' ) and ' ' in l :
38- canonical_email , alias = [x for x in l .split (' ' )
39- if x .startswith ('<' )]
40- mapping [alias ] = canonical_email
37+ try :
38+ canonical_email , alias = re .match (
39+ r'[^#]*?(<.+>).*(<.+>).*' , l ).groups ()
40+ except AttributeError :
41+ continue
42+ mapping [alias ] = canonical_email
4143 return mapping
4244
4345
4446def canonicalize_emails (changelog , mapping ):
4547 """Takes in a string and an email alias mapping and replaces all
4648 instances of the aliases in the string with their real email.
4749 """
48- for alias , email in mapping .iteritems ():
49- changelog = changelog .replace (alias , email )
50+ for alias , email_address in mapping .iteritems ():
51+ changelog = changelog .replace (alias , email_address )
5052 return changelog
5153
5254
@@ -106,23 +108,17 @@ def parse_dependency_links(requirements_files=['requirements.txt',
106108 return dependency_links
107109
108110
109- def write_requirements ():
110- venv = os .environ .get ('VIRTUAL_ENV' , None )
111- if venv is not None :
112- with open ("requirements.txt" , "w" ) as req_file :
113- output = subprocess .Popen (["pip" , "-E" , venv , "freeze" , "-l" ],
114- stdout = subprocess .PIPE )
115- requirements = output .communicate ()[0 ].strip ()
116- req_file .write (requirements )
117-
118-
119- def _run_shell_command (cmd ):
111+ def _run_shell_command (cmd , throw_on_error = False ):
120112 if os .name == 'nt' :
121113 output = subprocess .Popen (["cmd.exe" , "/C" , cmd ],
122- stdout = subprocess .PIPE )
114+ stdout = subprocess .PIPE ,
115+ stderr = subprocess .PIPE )
123116 else :
124117 output = subprocess .Popen (["/bin/sh" , "-c" , cmd ],
125- stdout = subprocess .PIPE )
118+ stdout = subprocess .PIPE ,
119+ stderr = subprocess .PIPE )
120+ if output .returncode and throw_on_error :
121+ raise Exception ("%s returned %d" % cmd , output .returncode )
126122 out = output .communicate ()
127123 if len (out ) == 0 :
128124 return None
@@ -131,57 +127,6 @@ def _run_shell_command(cmd):
131127 return out [0 ].strip ()
132128
133129
134- def _get_git_next_version_suffix (branch_name ):
135- datestamp = datetime .datetime .now ().strftime ('%Y%m%d' )
136- if branch_name == 'milestone-proposed' :
137- revno_prefix = "r"
138- else :
139- revno_prefix = ""
140- _run_shell_command ("git fetch origin +refs/meta/*:refs/remotes/meta/*" )
141- milestone_cmd = "git show meta/openstack/release:%s" % branch_name
142- milestonever = _run_shell_command (milestone_cmd )
143- if milestonever :
144- first_half = "%s~%s" % (milestonever , datestamp )
145- else :
146- first_half = datestamp
147-
148- post_version = _get_git_post_version ()
149- # post version should look like:
150- # 0.1.1.4.gcc9e28a
151- # where the bit after the last . is the short sha, and the bit between
152- # the last and second to last is the revno count
153- (revno , sha ) = post_version .split ("." )[- 2 :]
154- second_half = "%s%s.%s" % (revno_prefix , revno , sha )
155- return "." .join ((first_half , second_half ))
156-
157-
158- def _get_git_current_tag ():
159- return _run_shell_command ("git tag --contains HEAD" )
160-
161-
162- def _get_git_tag_info ():
163- return _run_shell_command ("git describe --tags" )
164-
165-
166- def _get_git_post_version ():
167- current_tag = _get_git_current_tag ()
168- if current_tag is not None :
169- return current_tag
170- else :
171- tag_info = _get_git_tag_info ()
172- if tag_info is None :
173- base_version = "0.0"
174- cmd = "git --no-pager log --oneline"
175- out = _run_shell_command (cmd )
176- revno = len (out .split ("\n " ))
177- sha = _run_shell_command ("git describe --always" )
178- else :
179- tag_infos = tag_info .split ("-" )
180- base_version = "-" .join (tag_infos [:- 2 ])
181- (revno , sha ) = tag_infos [- 2 :]
182- return "%s.%s.%s" % (base_version , revno , sha )
183-
184-
185130def write_git_changelog ():
186131 """Write a changelog based on the git changelog."""
187132 new_changelog = 'ChangeLog'
@@ -227,26 +172,6 @@ def generate_authors():
227172"""
228173
229174
230- def read_versioninfo (project ):
231- """Read the versioninfo file. If it doesn't exist, we're in a github
232- zipball, and there's really no way to know what version we really
233- are, but that should be ok, because the utility of that should be
234- just about nil if this code path is in use in the first place."""
235- versioninfo_path = os .path .join (project , 'versioninfo' )
236- if os .path .exists (versioninfo_path ):
237- with open (versioninfo_path , 'r' ) as vinfo :
238- version = vinfo .read ().strip ()
239- else :
240- version = "0.0.0"
241- return version
242-
243-
244- def write_versioninfo (project , version ):
245- """Write a simple file containing the version of the package."""
246- with open (os .path .join (project , 'versioninfo' ), 'w' ) as fil :
247- fil .write ("%s\n " % version )
248-
249-
250175def get_cmdclass ():
251176 """Return dict of commands to run from setup.py."""
252177
@@ -276,6 +201,9 @@ def run(self):
276201 from sphinx .setup_command import BuildDoc
277202
278203 class LocalBuildDoc (BuildDoc ):
204+
205+ builders = ['html' , 'man' ]
206+
279207 def generate_autoindex (self ):
280208 print "**Autodocumenting from %s" % os .path .abspath (os .curdir )
281209 modules = {}
@@ -311,56 +239,97 @@ def run(self):
311239 if not os .getenv ('SPHINX_DEBUG' ):
312240 self .generate_autoindex ()
313241
314- for builder in [ 'html' , 'man' ] :
242+ for builder in self . builders :
315243 self .builder = builder
316244 self .finalize_options ()
317245 self .project = self .distribution .get_name ()
318246 self .version = self .distribution .get_version ()
319247 self .release = self .distribution .get_version ()
320248 BuildDoc .run (self )
249+
250+ class LocalBuildLatex (LocalBuildDoc ):
251+ builders = ['latex' ]
252+
321253 cmdclass ['build_sphinx' ] = LocalBuildDoc
254+ cmdclass ['build_sphinx_latex' ] = LocalBuildLatex
322255 except ImportError :
323256 pass
324257
325258 return cmdclass
326259
327260
328- def get_git_branchname ():
329- for branch in _run_shell_command ("git branch --color=never" ).split ("\n " ):
330- if branch .startswith ('*' ):
331- _branch_name = branch .split ()[1 ].strip ()
332- if _branch_name == "(no" :
333- _branch_name = "no-branch"
334- return _branch_name
261+ def _get_revno ():
262+ """Return the number of commits since the most recent tag.
335263
264+ We use git-describe to find this out, but if there are no
265+ tags then we fall back to counting commits since the beginning
266+ of time.
267+ """
268+ describe = _run_shell_command ("git describe --always" )
269+ if "-" in describe :
270+ return describe .rsplit ("-" , 2 )[- 2 ]
336271
337- def get_pre_version (projectname , base_version ):
338- """Return a version which is leading up to a version that will
339- be released in the future."""
340- if os .path .isdir ('.git' ):
341- current_tag = _get_git_current_tag ()
342- if current_tag is not None :
343- version = current_tag
344- else :
345- branch_name = os .getenv ('BRANCHNAME' ,
346- os .getenv ('GERRIT_REFNAME' ,
347- get_git_branchname ()))
348- version_suffix = _get_git_next_version_suffix (branch_name )
349- version = "%s~%s" % (base_version , version_suffix )
350- write_versioninfo (projectname , version )
351- return version
352- else :
353- version = read_versioninfo (projectname )
354- return version
272+ # no tags found
273+ revlist = _run_shell_command ("git rev-list --abbrev-commit HEAD" )
274+ return len (revlist .splitlines ())
355275
356276
357- def get_post_version ( projectname ):
277+ def get_version_from_git ( pre_version ):
358278 """Return a version which is equal to the tag that's on the current
359279 revision if there is one, or tag plus number of additional revisions
360280 if the current revision has no tag."""
361281
362282 if os .path .isdir ('.git' ):
363- version = _get_git_post_version ()
364- write_versioninfo (projectname , version )
283+ if pre_version :
284+ try :
285+ return _run_shell_command (
286+ "git describe --exact-match" ,
287+ throw_on_error = True ).replace ('-' , '.' )
288+ except Exception :
289+ sha = _run_shell_command ("git log -n1 --pretty=format:%h" )
290+ return "%s.a%s.g%s" % (pre_version , _get_revno (), sha )
291+ else :
292+ return _run_shell_command (
293+ "git describe --always" ).replace ('-' , '.' )
294+ return None
295+
296+
297+ def get_version_from_pkg_info (package_name ):
298+ """Get the version from PKG-INFO file if we can."""
299+ try :
300+ pkg_info_file = open ('PKG-INFO' , 'r' )
301+ except (IOError , OSError ):
302+ return None
303+ try :
304+ pkg_info = email .message_from_file (pkg_info_file )
305+ except email .MessageError :
306+ return None
307+ # Check to make sure we're in our own dir
308+ if pkg_info .get ('Name' , None ) != package_name :
309+ return None
310+ return pkg_info .get ('Version' , None )
311+
312+
313+ def get_version (package_name , pre_version = None ):
314+ """Get the version of the project. First, try getting it from PKG-INFO, if
315+ it exists. If it does, that means we're in a distribution tarball or that
316+ install has happened. Otherwise, if there is no PKG-INFO file, pull the
317+ version from git.
318+
319+ We do not support setup.py version sanity in git archive tarballs, nor do
320+ we support packagers directly sucking our git repo into theirs. We expect
321+ that a source tarball be made from our git repo - or that if someone wants
322+ to make a source tarball from a fork of our repo with additional tags in it
323+ that they understand and desire the results of doing that.
324+ """
325+ version = os .environ .get ("OSLO_PACKAGE_VERSION" , None )
326+ if version :
327+ return version
328+ version = get_version_from_pkg_info (package_name )
329+ if version :
330+ return version
331+ version = get_version_from_git (pre_version )
332+ if version :
365333 return version
366- return read_versioninfo (projectname )
334+ raise Exception ("Versioning for this project requires either an sdist"
335+ " tarball, or access to an upstream git repository." )
0 commit comments