view silvermirror/hg.py @ 31:2adda506392b

STUB: silvermirror/hg.py
author Jeff Hammel <k0scist@gmail.com>
date Fri, 31 Jan 2014 20:34:34 -0800
parents 19ee8dfe2325
children fa1fe03ad924
line wrap: on
line source

#!/usr/bin/env python

"""
stub for the hg backend of silvermirror
"""

import hglib # http://mercurial.selenic.com/wiki/PythonHglib
import os
import sys
import argparse

_import_error = None
try:
    import lxml.html
except ImportError as _import_error:
    pass


def update(host, path):
    """
    get changes from host on path
    """
    url = '%s/%s' % (host, path)
    try:
        repo = hg.repository(path)
        print ('Updating {}:'.format(path))
    except Exception, e:
        repo = hg.repository(_ui, url)
        print ('Cloning {} -> {}'.format(url, path))
        commands.clone(_ui, repo, pull=False, uncompressed=False, rev=None, noupdate=False)
        return

    commands.pull(_ui, repo, url, rev=None, force=False, update=True)

# TODO: local repository
# def repositories(path):
#     """
#     return all hg repositories in a path
#     """

#     ui = ui.ui()
#     files = [ os.path.join(path, f) for f in os.listdir(path) ]
#     directories = [ f for f in files if os.path.isdir(f) ]

#     repos = []
#     for d in directories:
#         try:
#             repo = hg.repository(ui, d)
#             repos.append(os.path.basename(d))
#         except mercurial.repo.RepoError:
#             pass
#     return repos

def repositories(url):
    """
    returns the list of repositories under a URL of an hg server
    """
    element = lxml.html.parse(url)
    tds = element.xpath('//tr[position() > 1]/td[1]')
    repos = [i.text_content() for i in tds]
    return repos


def main(args=sys.argv[1:]):
    """CLI"""

    # parse command line
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('host',
                      help="URL of mercurial repository index page")
    parser.add_argument('-d', '--directory', dest='directory',
                        default=os.path.join(os.environ['HOME'], 'hg'),
                        help="base directory to clone/update to [DEFAULT: %(default)s]")
    parser.add_argument('--list', dest='list',
                      action='store_true', default=False,
                      help="list repositories and exit")
    options = parser.parse_args(args)
    if _import_error is not None:
        # XXX better error handling
        parser.error("Must have hglib and lxml package to use, sorry: {}".format(_import_error))

    # kill trailing slash
    options.host = options.host.rstrip('/')

    # get repositories
    repos = repositories(options.host)
    if options.list:
        for repo in repos:
            print repo
        sys.exit(0)

    # clone/update repos to directory
    if not os.path.exists(options.directory):
        os.mkdir(options.directory)
    for repo in repos:
        update(options.host, repo)

if __name__ == '__main__':
    main()