view silvermirror/hg.py @ 6:c999b2f16159

adding functionality to update/clone a bunch of hg repos
author k0s <k0scist@gmail.com>
date Thu, 15 Oct 2009 15:27:05 -0400
parents 660c74f33ed2
children 0da780dd81d0
line wrap: on
line source

#!/usr/bin/env python
"""
stub for the hg backend of silvermirror
"""

import lxml.html
import mercurial
import os
import sys
from mercurial import commands, hg, ui
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 mercurial.repo.RepoError:
        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)

# 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 reposotories 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 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)

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

if __name__ == '__main__':
    main()