view silvermirror/hg.py @ 13:584a847d2491

note on FF sync
author Jeff Hammel <jhammel@mozilla.com>
date Sat, 09 Apr 2011 12:10:19 -0700
parents 5a909090fb24
children f8edfc9c28ba
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 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)

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

    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()