# Copyright (C) 2006, 2008 Aaron Bentley
# <aaron@aaronbentley.com>
#
#    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 bzrlib import ui
from bzrlib.bzrdir import BzrDir
from bzrlib.config import LocationConfig
from bzrlib.errors import BzrCommandError, NoSuchFile
from bzrlib.osutils import pathjoin, basename, abspath
from bzrlib.transport import get_transport
from bzrlib.workingtree import WorkingTree
from bzrlib.urlutils import derive_to_location

def cbranch(from_location, to_location=None, revision=None,
            lightweight=False, files_from=None, hardlink=False):
    if to_location is None:
        to_location = derive_to_location(from_location)
    config = LocationConfig(abspath(to_location))
    b_loc = config.get_user_option("cbranch_target")
    if b_loc is None:
        b_root = config.get_user_option("cbranch_root")
        if b_root is None:
            raise BzrCommandError("Can't find cbranch_target in"
                                  " locations.conf")
        b_loc = pathjoin(b_root, basename(to_location))
    accelerator_tree, old_branch = BzrDir.open_tree_or_branch(from_location)
    if files_from is not None:
        accelerator_tree = WorkingTree.open(files_from)
    if revision is None or len(revision) == 0:
        revision_id = old_branch.last_revision()
    elif len(revision) == 1:
        revision_id = revision[0].in_history(old_branch)[1]
    else:
        raise BzrCommandError('At most one revision may be supplied.')
    b_transport = get_transport(b_loc)
    ensure_base_recursive(b_transport.clone('..'))
    pb = ui.ui_factory.nested_progress_bar()
    try:
        pb.update('Creating branch', 0, 2)
        new_branch = old_branch.bzrdir.sprout(b_loc, revision_id,
            accelerator_tree=accelerator_tree).open_branch()
        pb.update('Creating checkout', 1, 2)
        new_branch.create_checkout(to_location, lightweight=lightweight,
                                   accelerator_tree=accelerator_tree,
                                   hardlink=hardlink)
    finally:
        pb.finished()


def ensure_base_recursive(transport):
    """Ensure that the transport base and any its parents exist"""
    pending_transports = [transport]
    while len(pending_transports) > 0:
        transport = pending_transports.pop()
        try:
            transport.ensure_base()
        except NoSuchFile, e:
            pending_transports.append(transport)
            parent = transport.clone('..')
            if parent.base == transport.base:
                raise e
            pending_transports.append(parent)
