changeset 509:ac9c9e1a8022

setup: write out version info
author Augie Fackler <durin42@gmail.com>
date Tue, 15 Dec 2009 09:12:00 -0600
parents e5dedda7bee0
children 925ff8c5989c
files hgsubversion/util.py setup.py
diffstat 2 files changed, 90 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/hgsubversion/util.py
+++ b/hgsubversion/util.py
@@ -61,13 +61,18 @@ def islocalrepo(url):
 
 
 def version(ui):
-    """Guess the version of hgsubversion.
-    """
-    # TODO make this say something other than "unknown" for installed hgsubversion
-    dn = os.path.dirname
-    repo = hg.repository(ui, dn(dn(__file__)))
-    ver = repo.dirstate.parents()[0]
-    return node.hex(ver)[:12]
+    """Return version information if available."""
+    try:
+        import __version__
+        return __version__.version
+    except ImportError:
+        try:
+            dn = os.path.dirname
+            repo = hg.repository(ui, dn(dn(__file__)))
+            ver = repo.dirstate.parents()[0]
+            return node.hex(ver)[:12]
+        except:
+            return 'unknown'
 
 
 def normalize_url(url):
--- a/setup.py
+++ b/setup.py
@@ -1,7 +1,9 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 import os
+import subprocess
 import sys
+import time
 if not hasattr(sys, 'version_info') or sys.version_info < (2, 4, 0, 'final'):
     raise SystemExit("Mercurial requires python 2.4 or later.")
 
@@ -14,9 +16,84 @@ try:
 except ImportError:
     from distutils.core import setup
 
+def runcmd(cmd, env):
+    p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
+                         stderr=subprocess.PIPE, env=env)
+    out, err = p.communicate()
+    # If root is executing setup.py, but the repository is owned by
+    # another user (as in "sudo python setup.py install") we will get
+    # trust warnings since the .hg/hgrc file is untrusted. That is
+    # fine, we don't want to load it anyway.
+    err = [e for e in err.splitlines()
+           if not e.startswith('Not trusting file')]
+    if err:
+        return ''
+    return out
+
+
+version = ''
+
+if os.path.isdir('.hg'):
+    # Execute hg out of this directory with a custom environment which
+    # includes the pure Python modules in mercurial/pure. We also take
+    # care to not use any hgrc files and do no localization.
+    env = {'HGRCPATH': '',
+           'LANGUAGE': 'C'}
+    for copyenv in ('LD_LIBRARY_PATH', 'PYTHONPATH', 'PATH'):
+        if copyenv in os.environ:
+            env[copyenv] = os.environ[copyenv]
+    if 'SystemRoot' in os.environ:
+        # Copy SystemRoot into the custom environment for Python 2.6
+        # under Windows. Otherwise, the subprocess will fail with
+        # error 0xc0150004. See: http://bugs.python.org/issue3440
+        env['SystemRoot'] = os.environ['SystemRoot']
+    cmd = ['hg', 'id', '-i', '-t']
+    print runcmd(cmd, env)
+    l = runcmd(cmd, env).split()
+    print l
+    while len(l) > 1 and l[-1][0].isalpha(): # remove non-numbered tags
+        l.pop()
+    if len(l) > 1: # tag found
+        version = l[-1]
+        if l[0].endswith('+'): # propagate the dirty status to the tag
+            version += '+'
+    elif len(l) == 1: # no tag found
+        cmd = ['hg', 'parents', '--template',
+               '{latesttag}+{latesttagdistance}-']
+        version = runcmd(cmd, env) + l[0]
+    if not version:
+        version = runcmd(['hg', 'parents', '--template' '{node|short}\n'],
+                         env)
+        print 'xxx', version
+        if version:
+            version = version.split()[0]
+    if version.endswith('+'):
+        version += time.strftime('%Y%m%d')
+elif os.path.exists('.hg_archival.txt'):
+    kw = dict([t.strip() for t in l.split(':', 1)]
+              for l in open('.hg_archival.txt'))
+    if 'tag' in kw:
+        version =  kw['tag']
+    elif 'latesttag' in kw:
+        version = '%(latesttag)s+%(latesttagdistance)s-%(node).12s' % kw
+    else:
+        version = kw.get('node', '')[:12]
+
+if version:
+    f = open("hgsubversion/__version__.py", "w")
+    f.write('# this file is autogenerated by setup.py\n')
+    f.write('version = "%s"\n' % version)
+    f.close()
+
+try:
+    from hgsubversion import __version__
+    version = __version__.version
+except ImportError:
+    version = 'unknown'
+
 setup(
     name = 'hgsubversion',
-    version = '0.0.1',
+    version = version,
     url = 'http://bitbucket.org/durin42/hgsubversion',
     license = 'GNU GPL',
     author = 'Augie Fackler, others',