view silvermirror/hg.py @ 32:fa1fe03ad924

STUB: silvermirror/hg.py
author Jeff Hammel <k0scist@gmail.com>
date Fri, 31 Jan 2014 21:05:34 -0800
parents 2adda506392b
children d5e0bce5e411
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
from hglib.error import ServerError

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


def update(source, path):
    """
    get changes from host on path
    """
    try:
        repo = hglib.open(path)
        print ('Updating {}:'.format(path))
        repo.pull(host, update=True, insecure=True)
    except ServerError:
        print ('Cloning {} -> {}'.format(url, path))
        repo = hglib.clone(source, path)


# 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:
        dest = os.path.join(options.directory, repo)
        update(options.host, dest)

if __name__ == '__main__':
    main()