# Copyright (C) 2005-2009, 2011-2013 Aaron Bentley <aaron@aaronbentley.com>
# Copyright (C) 2007 John Arbash Meinel
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
from contextlib import contextmanager
import re

from bzrlib import urlutils
from bzrlib.errors import (
    BzrCommandError,
    NotBranchError,
    NoSuchFile,
    )
from bzrlib.bzrdir import BzrDir
from bzrlib.transport import get_transport


@contextmanager
def read_locked(lockable):
    """Read-lock a tree, branch or repository in this context."""
    lockable.lock_read()
    try:
        yield lockable
    finally:
        lockable.unlock()


def short_committer(committer):
    new_committer = re.sub('<.*>', '', committer).strip(' ')
    if len(new_committer) < 2:
        return committer
    return new_committer


def apache_ls(t):
    """Screen-scrape Apache listings"""
    apache_dir = '<img border="0" src="/icons/folder.gif" alt="[dir]">'\
        ' <a href="'
    t = t.clone()
    t._remote_path = lambda x: t.base
    try:
        lines = t.get('')
    except NoSuchFile:
        return
    expr = re.compile('<a[^>]*href="([^>]*)\/"[^>]*>', flags=re.I)
    for line in lines:
        match = expr.search(line)
        if match is None:
            continue
        url = match.group(1)
        if url.startswith('http://') or url.startswith('/') or '../' in url:
            continue
        if '?' in url:
            continue
        yield url.rstrip('/')


def list_branches(t):
    def is_inside(branch):
        return bool(branch.base.startswith(t.base))

    if t.base.startswith('http://'):
        def evaluate(bzrdir):
            try:
                branch = bzrdir.open_branch()
                if is_inside(branch):
                    return True, branch
                else:
                    return True, None
            except NotBranchError:
                return True, None
        return [b for b in BzrDir.find_bzrdirs(t, list_current=apache_ls,
                evaluate=evaluate) if b is not None]
    elif not t.listable():
        raise BzrCommandError("Can't list this type of location.")
    return [b for b in BzrDir.find_branches(t) if is_inside(b)]


def evaluate_branch_tree(bzrdir):
    try:
        tree, branch = bzrdir._get_tree_branch()
    except NotBranchError:
        return True, None
    else:
        return True, (branch, tree)


def iter_branch_tree(t, lister=None):
    return (x for x in BzrDir.find_bzrdirs(t, evaluate=evaluate_branch_tree,
            list_current=lister) if x is not None)


def open_from_url(location):
    location = urlutils.normalize_url(location)
    dirname, basename = urlutils.split(location)
    if location.endswith('/') and not basename.endswith('/'):
        basename += '/'
    return get_transport(dirname).get(basename)


def run_tests():
    import doctest
    result = doctest.testmod()
    if result[1] > 0:
        if result[0] == 0:
            print "All tests passed"
    else:
        print "No tests to run"
if __name__ == "__main__":
    run_tests()
