view silvermirror/hg.py @ 27:a648f57b1921

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

#!/usr/bin/env python

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

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
    """
    _ui = ui.ui()
    url = '%s/%s' % (host, path)
    try:
        repo = hg.repository(_ui, path)
        print 'Updating %s:' % path
    except Exception, e:
        import pdb;pdb.set_trace()
        repo = hg.repository(_ui, url)
        print 'Cloning %s:' % 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:
# 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', dest='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]")
    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()