Support for 'hg --version'. setup.py stores version from hg repository.
authorThomas Arendsen Hein <thomas@intevation.de>
Sat, 18 Jun 2005 16:32:41 +0100
changeset 423 25afb21d97ba5fd6dabb7dee41b0a4e08bbf2bea
parent 396 8f8bb77d560e70bcc95577e4dfa877df18d876ab
child 424 9294dce4b633fedca293b22858431b9acfc61245
push id1
push usergszorc@mozilla.com
push dateWed, 18 Mar 2015 16:34:57 +0000
Support for 'hg --version'. setup.py stores version from hg repository. -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Support for 'hg --version'. setup.py stores version from hg repository. manifest hash: c69058298ea12035f2cf356f987ba2fb5ff4bbae -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) iD8DBQFCtD6ZW7P1GVgWeRoRAnGHAKCLscthht2UlBEMDmxL9cku4PlcswCffOVo wTOhYkW4Ie5+8bdmL8EqsvY= =uGpn -----END PGP SIGNATURE-----
.hgignore
TODO
mercurial/commands.py
mercurial/version.py
setup.py
tests/test-help
tests/test-help.out
--- a/.hgignore
+++ b/.hgignore
@@ -2,9 +2,10 @@
 .*\.rej
 .*~
 .*\.so
 .*pyc
 build/.*
 dist/
 MANIFEST$
 .pc/
-patches/
\ No newline at end of file
+patches/
+mercurial/__version__.py$
--- a/TODO
+++ b/TODO
@@ -1,17 +1,17 @@
 General:
 - Better documentation
 - More regression tests
 - More specific try/except.
 - less code duplication, more code in the right places
 - python 2.2 support
 - better import support
 - export to git
-- Add standard files: AUTHORS, CREDITS, COPYING. ChangeLog? What else?
+- Add standard files: AUTHORS, CREDITS, ChangeLog? What else?
 - Code cleanup: apply http://python.org/peps/pep-0008.html
 
 Core:
 - difflib creating/removing files (fixed except dates: should be epoch)
 - directory foo.d or foo.i with existing file foo (use some quoting?)
 - get various options from hgrc (e.g. history always -v, tip always -q)
 - allow full decimal (part of) hash
   hg export 5005048662 -> OverflowError: long int too large to convert
@@ -28,17 +28,16 @@ Commands:
 - commands.py: number of args too much magic (e.g. in patch())
 - adding a tag with "hg tag foobar"
 - automatic pull fallback to old-http://
 - hg init|pull http://example.com doesn't say that no repo was found
 - hg annotate -u and hgweb annotate with long $EMAIL
 - hg -v history doesn't show tkmerge as modified (removed).
 - hg import vs. hg patch in help etc., import is a reserved python
   word, PEP8 mentions trailing underscore as a convention for this.
-- version reporting (hg --version / version.py / setup.py etc.)
 - hg pull default in a subdir doesn't work, if it is a relative path
 - optionally only show merges (two parents or parent != changeset-1, etc.)
 
 Web:
 - show tags in hgweb
 - show parent changeset number in hgweb
 - optionally only show merges (two parents or parent != changeset-1, etc.)
 - one hgweb with many repos (another script)
--- a/mercurial/commands.py
+++ b/mercurial/commands.py
@@ -3,17 +3,17 @@
 # Copyright 2005 Matt Mackall <mpm@selenic.com>
 #
 # This software may be used and distributed according to the terms
 # of the GNU General Public License, incorporated herein by reference.
 
 import os, re, sys, signal
 import fancyopts, ui, hg
 from demandload import *
-demandload(globals(), "mdiff time hgweb traceback random signal errno")
+demandload(globals(), "mdiff time hgweb traceback random signal errno version")
 
 class UnknownCommand(Exception): pass
 
 def filterfiles(filters, files):
     l = [ x for x in files if x in filters ]
 
     for t in filters:
         if t and t[-1] != os.sep: t += os.sep
@@ -129,16 +129,26 @@ def show_changeset(ui, repo, rev=0, chan
         if ui.verbose:
             ui.status("description:\n")
             ui.status(description)
             ui.status("\n")
         else:
             ui.status("summary:     %s\n" % description.splitlines()[0])
     ui.status("\n")
 
+def show_version(ui):
+    """output version and copyright information"""
+    ui.write("Mercurial version %s\n" % version.get_version())
+    ui.status(
+        "\nCopyright (C) 2005 Matt Mackall <mpm@selenic.com>\n"
+        "This is free software; see the source for copying conditions. "
+        "There is NO\nwarranty; "
+        "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
+    )
+
 def help(ui, cmd=None):
     '''show help for a given command or all commands'''
     if cmd:
         try:
             i = find(cmd)
             ui.write("%s\n\n" % i[2])
 
             if i[1]:
@@ -151,32 +161,35 @@ def help(ui, cmd=None):
                     if c: ui.write('   %s\n' % c)
                 ui.write("\n")
 
             ui.write(i[0].__doc__, "\n")
         except UnknownCommand:
             ui.warn("hg: unknown command %s\n" % cmd)
         sys.exit(0)
     else:
-        ui.status('hg commands:\n\n')
+        if not ui.quiet:
+            show_version(ui)
+            ui.write('\n')
+        ui.write('hg commands:\n\n')
 
         h = {}
         for e in table.values():
             f = e[0]
             if f.__name__.startswith("debug"): continue
             d = ""
             if f.__doc__:
                 d = f.__doc__.splitlines(0)[0].rstrip()
             h[f.__name__] = d
 
         fns = h.keys()
         fns.sort()
         m = max(map(len, fns))
         for f in fns:
-            ui.status(' %-*s   %s\n' % (m, f, h[f]))
+            ui.write(' %-*s   %s\n' % (m, f, h[f]))
 
 # Commands start here, listed alphabetically
 
 def add(ui, repo, file, *files):
     '''add the specified files on the next commit'''
     repo.add(relpath(repo, (file,) + files))
 
 def addremove(ui, repo, *files):
@@ -674,17 +687,17 @@ table = {
                                       [('m', 'merge', None,
                                         'allow merging of conflicts'),
                                        ('C', 'clean', None,
                                         'overwrite locally modified files')],
                                        'hg update [options] [node]'),
     "verify": (verify, [], 'hg verify'),
     }
 
-norepo = "init branch help debugindex debugindexdot"
+norepo = "init version help debugindex debugindexdot"
 
 def find(cmd):
     i = None
     for e in table.keys():
         if re.match("(%s)$" % e, cmd):
             return table[e]
 
     raise UnknownCommand(cmd)
@@ -699,29 +712,34 @@ def run():
 
 def dispatch(args):
     options = {}
     opts = [('v', 'verbose', None, 'verbose'),
             ('d', 'debug', None, 'debug'),
             ('q', 'quiet', None, 'quiet'),
             ('p', 'profile', None, 'profile'),
             ('y', 'noninteractive', None, 'run non-interactively'),
+            ('', 'version', None, 'output version information and exit'),
             ]
 
     args = fancyopts.fancyopts(args, opts, options,
                                'hg [options] <command> [options] [files]')
 
     if not args:
         cmd = "help"
     else:
         cmd, args = args[0], args[1:]
 
     u = ui.ui(options["verbose"], options["debug"], options["quiet"],
            not options["noninteractive"])
 
+    if options["version"]:
+        show_version(u)
+        sys.exit(0)
+
     try:
         i = find(cmd)
     except UnknownCommand:
         u.warn("hg: unknown command '%s'\n" % cmd)
         help(u)
         sys.exit(1)
 
     signal.signal(signal.SIGTERM, catchterm)
new file mode 100644
--- /dev/null
+++ b/mercurial/version.py
@@ -0,0 +1,62 @@
+# Copyright (C) 2005 by Intevation GmbH
+# Author(s):
+# Thomas Arendsen Hein <thomas@intevation.de>
+#
+# This program is free software under the GNU GPL (>=v2)
+# Read the file COPYING coming with the software for details.
+
+"""
+Mercurial version
+"""
+
+import os
+import os.path
+import re
+import time
+
+unknown_version = 'unknown'
+
+def get_version():
+    """Return version information if available."""
+    try:
+        from mercurial.__version__ import version
+    except ImportError:
+        version = unknown_version
+    return version
+
+def write_version(version):
+    """Overwrite version file."""
+    filename = os.path.join(os.path.dirname(__file__), '__version__.py')
+    f = open(filename, 'w')
+    f.write("# This file is auto-generated.\n")
+    f.write("version = %r\n" % version)
+    f.close()
+
+def remember_version():
+    """Store version information."""
+    f = os.popen("hg identify 2>/dev/null")  # use real hg installation
+    ident = f.read()[:-1]
+    if not f.close() and ident:
+        ids = ident.split(' ', 1)
+        version = ids.pop(0)
+        if version[-1] == '+':
+            version = version[:-1]
+            modified = True
+        else:
+            modified = False
+        if version.isalnum() and ids:
+            for tag in ids[0].split('/'):
+                # is a tag is suitable as a version number?
+                if re.match(r'^(\d+\.)+[\w.-]+$', tag):
+                    version = tag
+                    break
+        if modified:
+            version += time.strftime('+%Y%m%d')
+    else:
+        version = unknown_version
+    write_version(version)
+
+def forget_version():
+    """Remove version information."""
+    write_version(unknown_version)
+
--- a/setup.py
+++ b/setup.py
@@ -4,29 +4,35 @@
 #
 # './setup.py install', or
 # './setup.py --help' for more options
 
 import glob
 from distutils.core import setup, Extension
 from distutils.command.install_data import install_data
 
+import mercurial.version
+
 class install_package_data(install_data):
     def finalize_options(self):
         self.set_undefined_options('install',
                                    ('install_lib', 'install_dir'))
         install_data.finalize_options(self)
 
-setup(name='mercurial',
-      version='0.5b',
-      author='Matt Mackall',
-      author_email='mpm@selenic.com',
-      url='http://selenic.com/mercurial',
-      description='scalable distributed SCM',
-      license='GNU GPL',
-      packages=['mercurial'],
-      ext_modules=[Extension('mercurial.mpatch', ['mercurial/mpatch.c'])],
-      data_files=[('mercurial/templates',
-                   ['templates/map'] +
-                   glob.glob('templates/map-*') +
-                   glob.glob('templates/*.tmpl'))], 
-      cmdclass = { 'install_data' : install_package_data },
-      scripts=['hg', 'hgmerge'])
+try:
+    mercurial.version.remember_version()
+    setup(name='mercurial',
+        version=mercurial.version.get_version(),
+        author='Matt Mackall',
+        author_email='mpm@selenic.com',
+        url='http://selenic.com/mercurial',
+        description='scalable distributed SCM',
+        license='GNU GPL',
+        packages=['mercurial'],
+        ext_modules=[Extension('mercurial.mpatch', ['mercurial/mpatch.c'])],
+        data_files=[('mercurial/templates',
+                    ['templates/map'] +
+                    glob.glob('templates/map-*') +
+                    glob.glob('templates/*.tmpl'))], 
+        cmdclass = { 'install_data' : install_package_data },
+        scripts=['hg', 'hgmerge'])
+finally:
+    mercurial.version.forget_version()
--- a/tests/test-help
+++ b/tests/test-help
@@ -1,11 +1,11 @@
 #!/bin/bash
 
 set -x
 
-hg help
+hg -q help
 hg add -h
 hg help diff
 hg help foo
-hg commands
+hg -q commands
 
-exit 0
\ No newline at end of file
+exit 0
--- a/tests/test-help.out
+++ b/tests/test-help.out
@@ -1,9 +1,9 @@
-+ hg help
++ hg -q help
 hg commands:
 
  add         add the specified files on the next commit
  addremove   add all new files, delete all missing files
  annotate    show changeset information per file line
  cat         output the latest or given revision of a file
  commit      commit the specified files or all outstanding changes
  copy        mark a file as copied or renamed for the next commit
@@ -40,17 +40,17 @@ add the specified files on the next comm
 hg diff [-r A] [-r B] [files]
 
  -r --rev 
    revision
 
 diff working directory (or selected files)
 + hg help foo
 hg: unknown command foo
-+ hg commands
++ hg -q commands
 hg: unknown command 'commands'
 hg commands:
 
  add         add the specified files on the next commit
  addremove   add all new files, delete all missing files
  annotate    show changeset information per file line
  cat         output the latest or given revision of a file
  commit      commit the specified files or all outstanding changes