client does not show version

add support for --version
update openstack.common to bring in latest openstack.common.version

Change-Id: Ic1e66ea1f1aa65039b79902b893d1b2474ecb63e
Fixes:bug1177573
This commit is contained in:
Gordon Chung
2013-05-07 18:05:12 -04:00
parent f375d940e9
commit 453f4d2a4b
5 changed files with 72 additions and 48 deletions

View File

@@ -9,23 +9,11 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import inspect from ceilometerclient.openstack.common import version
import os
def _get_ceilometerclient_version(): version_info = version.VersionInfo('python-ceilometerclient')
"""Read version from versioninfo file.""" try:
mod_abspath = inspect.getabsfile(inspect.currentframe()) __version__ = version_info.version_string()
ceilometerclient_path = os.path.dirname(mod_abspath) except AttributeError:
version_path = os.path.join(ceilometerclient_path, 'versioninfo') __version__ = None
if os.path.exists(version_path):
version = open(version_path).read().strip()
else:
version = "Unknown, couldn't find versioninfo file at %s"\
% version_path
return version
__version__ = _get_ceilometerclient_version()

View File

@@ -1,6 +1,6 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC. # Copyright 2011 OpenStack Foundation.
# All Rights Reserved. # All Rights Reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may # Licensed under the Apache License, Version 2.0 (the "License"); you may

View File

@@ -1,6 +1,6 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC. # Copyright 2011 OpenStack Foundation.
# Copyright 2012-2013 Hewlett-Packard Development Company, L.P. # Copyright 2012-2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved. # All Rights Reserved.
# #
@@ -20,6 +20,8 @@
Utilities with minimum-depends for use in setup.py Utilities with minimum-depends for use in setup.py
""" """
from __future__ import print_function
import email import email
import os import os
import re import re
@@ -43,6 +45,11 @@ def parse_mailmap(mailmap='.mailmap'):
return mapping return mapping
def _parse_git_mailmap(git_dir, mailmap='.mailmap'):
mailmap = os.path.join(os.path.dirname(git_dir), mailmap)
return parse_mailmap(mailmap)
def canonicalize_emails(changelog, mapping): def canonicalize_emails(changelog, mapping):
"""Takes in a string and an email alias mapping and replaces all """Takes in a string and an email alias mapping and replaces all
instances of the aliases in the string with their real email. instances of the aliases in the string with their real email.
@@ -117,9 +124,9 @@ def _run_shell_command(cmd, throw_on_error=False):
output = subprocess.Popen(["/bin/sh", "-c", cmd], output = subprocess.Popen(["/bin/sh", "-c", cmd],
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
out = output.communicate()
if output.returncode and throw_on_error: if output.returncode and throw_on_error:
raise Exception("%s returned %d" % cmd, output.returncode) raise Exception("%s returned %d" % cmd, output.returncode)
out = output.communicate()
if len(out) == 0: if len(out) == 0:
return None return None
if len(out[0].strip()) == 0: if len(out[0].strip()) == 0:
@@ -127,14 +134,26 @@ def _run_shell_command(cmd, throw_on_error=False):
return out[0].strip() return out[0].strip()
def _get_git_directory():
parent_dir = os.path.dirname(__file__)
while True:
git_dir = os.path.join(parent_dir, '.git')
if os.path.exists(git_dir):
return git_dir
parent_dir, child = os.path.split(parent_dir)
if not child: # reached to root dir
return None
def write_git_changelog(): def write_git_changelog():
"""Write a changelog based on the git changelog.""" """Write a changelog based on the git changelog."""
new_changelog = 'ChangeLog' new_changelog = 'ChangeLog'
git_dir = _get_git_directory()
if not os.getenv('SKIP_WRITE_GIT_CHANGELOG'): if not os.getenv('SKIP_WRITE_GIT_CHANGELOG'):
if os.path.isdir('.git'): if git_dir:
git_log_cmd = 'git log --stat' git_log_cmd = 'git --git-dir=%s log' % git_dir
changelog = _run_shell_command(git_log_cmd) changelog = _run_shell_command(git_log_cmd)
mailmap = parse_mailmap() mailmap = _parse_git_mailmap(git_dir)
with open(new_changelog, "w") as changelog_file: with open(new_changelog, "w") as changelog_file:
changelog_file.write(canonicalize_emails(changelog, mailmap)) changelog_file.write(canonicalize_emails(changelog, mailmap))
else: else:
@@ -146,13 +165,23 @@ def generate_authors():
jenkins_email = 'jenkins@review.(openstack|stackforge).org' jenkins_email = 'jenkins@review.(openstack|stackforge).org'
old_authors = 'AUTHORS.in' old_authors = 'AUTHORS.in'
new_authors = 'AUTHORS' new_authors = 'AUTHORS'
git_dir = _get_git_directory()
if not os.getenv('SKIP_GENERATE_AUTHORS'): if not os.getenv('SKIP_GENERATE_AUTHORS'):
if os.path.isdir('.git'): if git_dir:
# don't include jenkins email address in AUTHORS file # don't include jenkins email address in AUTHORS file
git_log_cmd = ("git log --format='%aN <%aE>' | sort -u | " git_log_cmd = ("git --git-dir=" + git_dir +
" log --format='%aN <%aE>' | sort -u | "
"egrep -v '" + jenkins_email + "'") "egrep -v '" + jenkins_email + "'")
changelog = _run_shell_command(git_log_cmd) changelog = _run_shell_command(git_log_cmd)
mailmap = parse_mailmap() signed_cmd = ("git --git-dir=" + git_dir +
" log | grep -i Co-authored-by: | sort -u")
signed_entries = _run_shell_command(signed_cmd)
if signed_entries:
new_entries = "\n".join(
[signed.split(":", 1)[1].strip()
for signed in signed_entries.split("\n") if signed])
changelog = "\n".join((changelog, new_entries))
mailmap = _parse_git_mailmap(git_dir)
with open(new_authors, 'w') as new_authors_fh: with open(new_authors, 'w') as new_authors_fh:
new_authors_fh.write(canonicalize_emails(changelog, mailmap)) new_authors_fh.write(canonicalize_emails(changelog, mailmap))
if os.path.exists(old_authors): if os.path.exists(old_authors):
@@ -205,7 +234,7 @@ def get_cmdclass():
builders = ['html', 'man'] builders = ['html', 'man']
def generate_autoindex(self): def generate_autoindex(self):
print "**Autodocumenting from %s" % os.path.abspath(os.curdir) print("**Autodocumenting from %s" % os.path.abspath(os.curdir))
modules = {} modules = {}
option_dict = self.distribution.get_option_dict('build_sphinx') option_dict = self.distribution.get_option_dict('build_sphinx')
source_dir = os.path.join(option_dict['source_dir'][1], 'api') source_dir = os.path.join(option_dict['source_dir'][1], 'api')
@@ -230,7 +259,7 @@ def get_cmdclass():
values = dict(module=module, heading=heading, values = dict(module=module, heading=heading,
underline=underline) underline=underline)
print "Generating %s" % output_filename print("Generating %s" % output_filename)
with open(output_filename, 'w') as output_file: with open(output_filename, 'w') as output_file:
output_file.write(_rst_template % values) output_file.write(_rst_template % values)
autoindex.write(" %s.rst\n" % module) autoindex.write(" %s.rst\n" % module)
@@ -258,43 +287,48 @@ def get_cmdclass():
return cmdclass return cmdclass
def _get_revno(): def _get_revno(git_dir):
"""Return the number of commits since the most recent tag. """Return the number of commits since the most recent tag.
We use git-describe to find this out, but if there are no We use git-describe to find this out, but if there are no
tags then we fall back to counting commits since the beginning tags then we fall back to counting commits since the beginning
of time. of time.
""" """
describe = _run_shell_command("git describe --always") describe = _run_shell_command(
"git --git-dir=%s describe --always" % git_dir)
if "-" in describe: if "-" in describe:
return describe.rsplit("-", 2)[-2] return describe.rsplit("-", 2)[-2]
# no tags found # no tags found
revlist = _run_shell_command("git rev-list --abbrev-commit HEAD") revlist = _run_shell_command(
"git --git-dir=%s rev-list --abbrev-commit HEAD" % git_dir)
return len(revlist.splitlines()) return len(revlist.splitlines())
def get_version_from_git(pre_version): def _get_version_from_git(pre_version):
"""Return a version which is equal to the tag that's on the current """Return a version which is equal to the tag that's on the current
revision if there is one, or tag plus number of additional revisions revision if there is one, or tag plus number of additional revisions
if the current revision has no tag.""" if the current revision has no tag."""
if os.path.isdir('.git'): git_dir = _get_git_directory()
if git_dir:
if pre_version: if pre_version:
try: try:
return _run_shell_command( return _run_shell_command(
"git describe --exact-match", "git --git-dir=" + git_dir + " describe --exact-match",
throw_on_error=True).replace('-', '.') throw_on_error=True).replace('-', '.')
except Exception: except Exception:
sha = _run_shell_command("git log -n1 --pretty=format:%h") sha = _run_shell_command(
return "%s.a%s.g%s" % (pre_version, _get_revno(), sha) "git --git-dir=" + git_dir + " log -n1 --pretty=format:%h")
return "%s.a%s.g%s" % (pre_version, _get_revno(git_dir), sha)
else: else:
return _run_shell_command( return _run_shell_command(
"git describe --always").replace('-', '.') "git --git-dir=" + git_dir + " describe --always").replace(
'-', '.')
return None return None
def get_version_from_pkg_info(package_name): def _get_version_from_pkg_info(package_name):
"""Get the version from PKG-INFO file if we can.""" """Get the version from PKG-INFO file if we can."""
try: try:
pkg_info_file = open('PKG-INFO', 'r') pkg_info_file = open('PKG-INFO', 'r')
@@ -325,10 +359,10 @@ def get_version(package_name, pre_version=None):
version = os.environ.get("OSLO_PACKAGE_VERSION", None) version = os.environ.get("OSLO_PACKAGE_VERSION", None)
if version: if version:
return version return version
version = get_version_from_pkg_info(package_name) version = _get_version_from_pkg_info(package_name)
if version: if version:
return version return version
version = get_version_from_git(pre_version) version = _get_version_from_git(pre_version)
if version: if version:
return version return version
raise Exception("Versioning for this project requires either an sdist" raise Exception("Versioning for this project requires either an sdist"

View File

@@ -1,5 +1,5 @@
# Copyright 2012 OpenStack LLC # Copyright 2012 OpenStack Foundation
# Copyright 2012-2013 Hewlett-Packard Development Company, L.P. # Copyright 2012-2013 Hewlett-Packard Development Company, L.P.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may # Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -49,11 +49,11 @@ class VersionInfo(object):
provider = pkg_resources.get_provider(requirement) provider = pkg_resources.get_provider(requirement)
return provider.version return provider.version
except pkg_resources.DistributionNotFound: except pkg_resources.DistributionNotFound:
# The most likely cause for this is running tests in a tree with # The most likely cause for this is running tests in a tree
# produced from a tarball where the package itself has not been # produced from a tarball where the package itself has not been
# installed into anything. Check for a PKG-INFO file. # installed into anything. Revert to setup-time logic.
from ceilometerclient.openstack.common import setup from ceilometerclient.openstack.common import setup
return setup.get_version_from_pkg_info(self.package) return setup.get_version(self.package)
def release_string(self): def release_string(self):
"""Return the full version of the package including suffixes indicating """Return the full version of the package including suffixes indicating

View File

@@ -21,12 +21,10 @@ import sys
from keystoneclient.v2_0 import client as ksclient from keystoneclient.v2_0 import client as ksclient
import ceilometerclient
from ceilometerclient import exc from ceilometerclient import exc
from ceilometerclient import client as ceilometerclient
from ceilometerclient.common import utils from ceilometerclient.common import utils
logger = logging.getLogger(__name__)
class CeilometerShell(object): class CeilometerShell(object):
@@ -46,6 +44,10 @@ class CeilometerShell(object):
help=argparse.SUPPRESS, help=argparse.SUPPRESS,
) )
parser.add_argument('--version',
action='version',
version=ceilometerclient.__version__)
parser.add_argument('-d', '--debug', parser.add_argument('-d', '--debug',
default=bool(utils.env('CEILOMETERCLIENT_DEBUG')), default=bool(utils.env('CEILOMETERCLIENT_DEBUG')),
action='store_true', action='store_true',