view silvermirror/hg.py @ 24:183cee927d8b

STUB: silvermirror/hg.py
author Jeff Hammel <k0scist@gmail.com>
date Thu, 30 Jan 2014 20:31:03 -0800
parents f8edfc9c28ba
children cedf9a0e3d61
line wrap: on
line source

#!/usr/bin/env python

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

try:
    import lxml.html
    import mercurial
    from mercurial import commands, hg, ui
    requirements_fulfilled = True
except ImportError as e:
    _import_error = e
    requirements_fulfilled = False

import os
import sys
from optparse import OptionParser

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:
        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:]):
    parser = OptionParser()
    parser.add_option('-H', '--host', dest='host')
    parser.add_option('-d', '--directory', dest='directory',
                      default=os.path.join(os.environ['HOME'], 'hg'))
    parser.add_option('--list', dest='list',
                      action='store_true', default=False)
    options, args = parser.parse_args(args)
    if not requirements_fulfilled:
        # Hack; this should all be better o_O
        parser.error("Must have mercurial and lxml packages to use, sorry")
    if not options.host:
        parser.print_usage()
        parser.exit()

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

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

    if not os.path.exists(options.directory):
        os.mkdir(options.directory)

    os.chdir(options.directory)
    for repo in repos:
        update(options.host, repo)

if __name__ == '__main__':
    main()