Ejemplo n.º 1
0
 def test_nicks(self):
     """Test explicit and implicit branch nicknames.
     
     Nicknames are implicitly the name of the branch's directory, unless an
     explicit nickname is set.  That is, an explicit nickname always
     overrides the implicit one.
     """
     t = get_transport(self.get_url())
     branch = self.make_branch('bzr.dev')
     # The nick will be 'bzr.dev', because there is no explicit nick set.
     self.assertEqual(branch.nick, 'bzr.dev')
     # Move the branch to a different directory, 'bzr.ab'.  Now that branch
     # will report its nick as 'bzr.ab'.
     t.move('bzr.dev', 'bzr.ab')
     branch = Branch.open(self.get_url('bzr.ab'))
     self.assertEqual(branch.nick, 'bzr.ab')
     # Set the branch nick explicitly.  This will ensure there's a branch
     # config file in the branch.
     branch.nick = "Aaron's branch"
     if not isinstance(branch, remote.RemoteBranch):
         self.failUnless(branch._transport.has("branch.conf"))
     # Because the nick has been set explicitly, the nick is now always
     # "Aaron's branch", regardless of directory name.
     self.assertEqual(branch.nick, "Aaron's branch")
     t.move('bzr.ab', 'integration')
     branch = Branch.open(self.get_url('integration'))
     self.assertEqual(branch.nick, "Aaron's branch")
     branch.nick = u"\u1234"
     self.assertEqual(branch.nick, u"\u1234")
Ejemplo n.º 2
0
 def test_nicks(self):
     """Test explicit and implicit branch nicknames.
     
     Nicknames are implicitly the name of the branch's directory, unless an
     explicit nickname is set.  That is, an explicit nickname always
     overrides the implicit one.
     """
     t = get_transport(self.get_url())
     branch = self.make_branch('bzr.dev')
     # The nick will be 'bzr.dev', because there is no explicit nick set.
     self.assertEqual(branch.nick, 'bzr.dev')
     # Move the branch to a different directory, 'bzr.ab'.  Now that branch
     # will report its nick as 'bzr.ab'.
     t.move('bzr.dev', 'bzr.ab')
     branch = Branch.open(self.get_url('bzr.ab'))
     self.assertEqual(branch.nick, 'bzr.ab')
     # Set the branch nick explicitly.  This will ensure there's a branch
     # config file in the branch.
     branch.nick = "Aaron's branch"
     if not isinstance(branch, remote.RemoteBranch):
         self.failUnless(branch._transport.has("branch.conf"))
     # Because the nick has been set explicitly, the nick is now always
     # "Aaron's branch", regardless of directory name.
     self.assertEqual(branch.nick, "Aaron's branch")
     t.move('bzr.ab', 'integration')
     branch = Branch.open(self.get_url('integration'))
     self.assertEqual(branch.nick, "Aaron's branch")
     branch.nick = u"\u1234"
     self.assertEqual(branch.nick, u"\u1234")
Ejemplo n.º 3
0
 def test_branch_push_pull_merge_copies_tags(self):
     t = self.make_branch_and_tree('branch1')
     t.commit(allow_pointless=True,
              message='initial commit',
              rev_id='first-revid')
     b1 = t.branch
     b1.tags.set_tag('tag1', 'first-revid')
     # branching copies the tag across
     self.run_bzr('branch branch1 branch2')
     b2 = Branch.open('branch2')
     self.assertEqual(b2.tags.lookup_tag('tag1'), 'first-revid')
     # make a new tag and pull it
     b1.tags.set_tag('tag2', 'twa')
     self.run_bzr('pull -d branch2 branch1')
     self.assertEqual(b2.tags.lookup_tag('tag2'), 'twa')
     # make a new tag and push it
     b1.tags.set_tag('tag3', 'san')
     self.run_bzr('push -d branch1 branch2')
     self.assertEqual(b2.tags.lookup_tag('tag3'), 'san')
     # make a new tag and merge it
     t.commit(allow_pointless=True,
              message='second commit',
              rev_id='second-revid')
     t2 = WorkingTree.open('branch2')
     t2.commit(allow_pointless=True, message='commit in second')
     b1.tags.set_tag('tag4', 'second-revid')
     self.run_bzr('merge -d branch2 branch1')
     self.assertEqual(b2.tags.lookup_tag('tag4'), 'second-revid')
     # pushing to a new location copies the tag across
     self.run_bzr('push -d branch1 branch3')
     b3 = Branch.open('branch3')
     self.assertEqual(b3.tags.lookup_tag('tag1'), 'first-revid')
Ejemplo n.º 4
0
 def test_branch_push_pull_merge_copies_tags(self):
     t = self.make_branch_and_tree('branch1')
     t.commit(allow_pointless=True, message='initial commit',
         rev_id='first-revid')
     b1 = t.branch
     b1.tags.set_tag('tag1', 'first-revid')
     # branching copies the tag across
     self.run_bzr('branch branch1 branch2')
     b2 = Branch.open('branch2')
     self.assertEquals(b2.tags.lookup_tag('tag1'), 'first-revid')
     # make a new tag and pull it
     b1.tags.set_tag('tag2', 'twa')
     self.run_bzr('pull -d branch2 branch1')
     self.assertEquals(b2.tags.lookup_tag('tag2'), 'twa')
     # make a new tag and push it
     b1.tags.set_tag('tag3', 'san')
     self.run_bzr('push -d branch1 branch2')
     self.assertEquals(b2.tags.lookup_tag('tag3'), 'san')
     # make a new tag and merge it
     t.commit(allow_pointless=True, message='second commit',
         rev_id='second-revid')
     t2 = WorkingTree.open('branch2')
     t2.commit(allow_pointless=True, message='commit in second')
     b1.tags.set_tag('tag4', 'second-revid')
     self.run_bzr('merge -d branch2 branch1')
     self.assertEquals(b2.tags.lookup_tag('tag4'), 'second-revid')
     # pushing to a new location copies the tag across
     self.run_bzr('push -d branch1 branch3')
     b3 = Branch.open('branch3')
     self.assertEquals(b3.tags.lookup_tag('tag1'), 'first-revid')
Ejemplo n.º 5
0
 def from_source_tree(cls, source_tree):
     """
     Initialize :class:`~versiontools.bzr_support.BzrIntegration` by
     pointing at the source tree.  Any file or directory inside the
     source tree may be used.
     """
     branch = None
     try:
         import bzrlib
         if bzrlib.__version__ >= (2, 2, 1):
             # Python 2.4 the with keyword is not supported
             # and so you need to use the context manager manually, sigh.
             library_state = bzrlib.initialize()
             library_state.__enter__()
             try:
                 from bzrlib.branch import Branch
                 branch = Branch.open_containing(source_tree)[0]
             finally:
                 library_state.__exit__(None, None, None)
         else:
             from bzrlib.branch import Branch
             branch = Branch.open_containing(source_tree)[0]
     except Exception:
         from versiontools import get_exception_message
         message = get_exception_message(*sys.exc_info())
         logging.debug("Unable to get branch revision because "
                       "directory %r is not a bzr branch. Erorr: %s",
                       (source_tree, message))
     if branch:
         return cls(branch)
Ejemplo n.º 6
0
    def check(self):
        """ See if a folder's contents were modified or created. """
        try:
            self.read_cache_file()
            local_branch = Branch.open_containing(self.folder)[0]
            remote_branch = Branch.open_containing(
                local_branch.get_parent())[0]
            if local_branch.get_parent() != None:
                self.remote_branch_label = local_branch.get_parent().replace(
                    "%7E", "~")
                self.local_extra, self.remote_extra = find_unmerged(
                    local_branch, remote_branch)

                if len(self.local_extra) != 0:
                    if int(self.local_extra[len(self.local_extra) -
                                            1][0]) > self.local_branch_:
                        self.actually_changed = True
                        self.write_cache_file()

                if len(self.remote_extra) != 0:
                    if int(self.remote_extra[len(self.remote_extra) -
                                             1][0]) > self.remote_branch_:
                        self.actually_changed = True
                        self.write_cache_file()

                if not self.local_extra and not self.remote_extra:
                    self.mark_as_read()
            else:
                self.set_error(
                    _("No parent branch available, you will not be notified of differences and changes."
                      ))

        except NotBranchError, e:
            self.set_error(str(e))
Ejemplo n.º 7
0
 def test_hook_does_not_interfere(self):
     # The transform_fallback_location hook does not interfere with regular
     # stacked branch access outside of safe_open.
     self.make_branch('stacked')
     self.make_branch('stacked-on')
     Branch.open('stacked').set_stacked_on_url('../stacked-on')
     Branch.open('stacked')
Ejemplo n.º 8
0
    def check(self):
        """ See if a folder's contents were modified or created. """
        try:
            self.read_cache_file()
            local_branch = Branch.open_containing(self.folder)[0]
            remote_branch = Branch.open_containing(local_branch.get_parent())[0]
            if local_branch.get_parent() != None:
                self.remote_branch_label = local_branch.get_parent().replace("%7E", "~")
                self.local_extra, self.remote_extra = find_unmerged(local_branch, remote_branch)

                if len(self.local_extra) != 0:
                    if int(self.local_extra[len(self.local_extra) - 1][0]) > self.local_branch_:
                        self.actually_changed = True
                        self.write_cache_file()

                if len(self.remote_extra) != 0:
                    if int(self.remote_extra[len(self.remote_extra) - 1][0]) > self.remote_branch_:
                        self.actually_changed = True
                        self.write_cache_file()

                if not self.local_extra and not self.remote_extra:
                    self.mark_as_read()
            else:
                self.set_error(_("No parent branch available, you will not be notified of differences and changes."))

        except NotBranchError, e:
            self.set_error(str(e))
Ejemplo n.º 9
0
 def from_source_tree(cls, source_tree):
     """
     Initialize :class:`~versiontools.bzr_support.BzrIntegration` by
     pointing at the source tree.  Any file or directory inside the
     source tree may be used.
     """
     branch = None
     try:
         import bzrlib
         if bzrlib.__version__ >= (2, 2, 1):
             # Python 2.4 the with keyword is not supported
             # and so you need to use the context manager manually, sigh.
             library_state = bzrlib.initialize()
             library_state.__enter__()
             try:
                 from bzrlib.branch import Branch
                 branch = Branch.open_containing(source_tree)[0]
             finally:
                 library_state.__exit__(None, None, None)
         else:
             from bzrlib.branch import Branch
             branch = Branch.open_containing(source_tree)[0]
     except Exception:
         from versiontools import get_exception_message
         message = get_exception_message(*sys.exc_info())
         logging.debug(
             "Unable to get branch revision because "
             "directory %r is not a bzr branch. Erorr: %s",
             (source_tree, message))
     if branch:
         return cls(branch)
Ejemplo n.º 10
0
def bzr_push(source, target=None):
    from bzrlib.branch import Branch
    try:
        branch = Branch.open(source)
    except:
        _logger.error(
            'Bzr push: The provided source branch (%s) can\'t be opened.' %
            source)
        return False

    if target:
        try:
            target = Branch.open(target)
        except:
            _logger.error(
                'Bzr push: The provided target branch (%s) can\'t be opened.' %
                target)
            return False
        try:
            return branch.push(target)
        except:
            _logger.error('Bzr push: failed. Exiting.')
    else:
        try:
            return branch.push()
        except:
            _logger.error('Bzr push: failed. Exiting.')
    return False
Ejemplo n.º 11
0
 def test_hook_does_not_interfere(self):
     # The transform_fallback_location hook does not interfere with regular
     # stacked branch access outside of safe_open.
     self.make_branch('stacked')
     self.make_branch('stacked-on')
     Branch.open('stacked').set_stacked_on_url('../stacked-on')
     Branch.open('stacked')
Ejemplo n.º 12
0
    def __update(self, name):
        if not os.path.exists(os.path.join(self.directory, name, '.bzr')):
            return self.checkout(name)

        charm_remote = self.__get_repository(name)
        local_branch = Branch.open(os.path.join(self.directory, name))
        remote_branch = Branch.open(charm_remote)
        local_branch.pull(remote_branch)
Ejemplo n.º 13
0
    def __update(self, name):
        if not os.path.exists(os.path.join(self.directory, name, '.bzr')):
            return self.checkout(name)

        charm_remote = self.__get_repository(name)
        local_branch = Branch.open(os.path.join(self.directory, name))
        remote_branch = Branch.open(charm_remote)
        local_branch.pull(remote_branch)
Ejemplo n.º 14
0
def is_versioned(cmd):
    from bzrlib.errors import NotBranchError
    try:
        from bzrlib.branch import Branch
        Branch.open(".")
        return True
    except NotBranchError:
        return False
Ejemplo n.º 15
0
 def test_notneeded_main_ahead(self):
     self.make_file('barbla', "bloe")
     self.run_bzr('add')
     self.run_bzr('commit -m bloe')
     os.chdir('../feature')
     self.assertEquals("Base branch is descendant of current branch. Pulling instead.\n",
         self.run_bzr('rebase ../main')[0])
     self.assertEquals(Branch.open("../feature").last_revision_info(),
                       Branch.open("../main").last_revision_info())
Ejemplo n.º 16
0
 def test_weaves_are_retrieved_once(self):
     self.build_tree(("source/", "source/file", "target/"))
     # This test depends on knit dasta storage.
     wt = self.make_branch_and_tree('source', format='dirstate-tags')
     branch = wt.branch
     wt.add(["file"], ["id"])
     wt.commit("added file")
     open("source/file", 'w').write("blah\n")
     wt.commit("changed file")
     target = BzrDir.create_branch_and_repo("target/")
     source = Branch.open(self.get_readonly_url("source/"))
     self.assertEqual(target.fetch(source), (2, []))
     # this is the path to the literal file. As format changes 
     # occur it needs to be updated. FIXME: ask the store for the
     # path.
     self.log("web server logs are:")
     http_logs = self.get_readonly_server().logs
     self.log('\n'.join(http_logs))
     # unfortunately this log entry is branch format specific. We could 
     # factor out the 'what files does this format use' to a method on the 
     # repository, which would let us to this generically. RBC 20060419
     # RBC 20080408: Or perhaps we can assert that no files are fully read
     # twice?
     self.assertEqual(1, self._count_log_matches('/ce/id.kndx', http_logs))
     self.assertEqual(1, self._count_log_matches('/ce/id.knit', http_logs))
     self.assertEqual(1, self._count_log_matches('inventory.kndx', http_logs))
     # this r-h check test will prevent regressions, but it currently already 
     # passes, before the patch to cache-rh is applied :[
     self.assertTrue(1 >= self._count_log_matches('revision-history',
                                                  http_logs))
     self.assertTrue(1 >= self._count_log_matches('last-revision',
                                                  http_logs))
     # FIXME naughty poking in there.
     self.get_readonly_server().logs = []
     # check there is nothing more to fetch.  We take care to re-use the
     # existing transport so that the request logs we're about to examine
     # aren't cluttered with redundant probes for a smart server.
     # XXX: Perhaps this further parameterisation: test http with smart
     # server, and test http without smart server?
     source = Branch.open(
         self.get_readonly_url("source/"),
         possible_transports=[source.bzrdir.root_transport])
     self.assertEqual(target.fetch(source), (0, []))
     # should make just two requests
     http_logs = self.get_readonly_server().logs
     self.log("web server logs are:")
     self.log('\n'.join(http_logs))
     self.assertEqual(1, self._count_log_matches('branch-format', http_logs))
     self.assertEqual(1, self._count_log_matches('branch/format', http_logs))
     self.assertEqual(1, self._count_log_matches('repository/format',
         http_logs))
     self.assertTrue(1 >= self._count_log_matches('revision-history',
                                                  http_logs))
     self.assertTrue(1 >= self._count_log_matches('last-revision',
                                                  http_logs))
     self.assertEqual(4, len(http_logs))
Ejemplo n.º 17
0
 def test_stacked_within_scheme(self):
     # A branch that is stacked on a URL of the same scheme is safe to
     # open.
     self.get_transport().mkdir('inside')
     self.make_branch('inside/stacked')
     self.make_branch('inside/stacked-on')
     scheme, get_chrooted_url = self.get_chrooted_scheme('inside')
     Branch.open(get_chrooted_url('stacked')).set_stacked_on_url(
         get_chrooted_url('stacked-on'))
     safe_open(scheme, get_chrooted_url('stacked'))
Ejemplo n.º 18
0
 def test_open_containing(self):
     self.assertRaises(NotBranchError, Branch.open_containing,
                       self.get_readonly_url(''))
     self.assertRaises(NotBranchError, Branch.open_containing,
                       self.get_readonly_url('g/p/q'))
     branch = self.make_branch('.')
     branch, relpath = Branch.open_containing(self.get_readonly_url(''))
     self.assertEqual('', relpath)
     branch, relpath = Branch.open_containing(self.get_readonly_url('g/p/q'))
     self.assertEqual('g/p/q', relpath)
Ejemplo n.º 19
0
 def test_stacked_within_scheme(self):
     # A branch that is stacked on a URL of the same scheme is safe to
     # open.
     self.get_transport().mkdir('inside')
     self.make_branch('inside/stacked')
     self.make_branch('inside/stacked-on')
     scheme, get_chrooted_url = self.get_chrooted_scheme('inside')
     Branch.open(get_chrooted_url('stacked')).set_stacked_on_url(
         get_chrooted_url('stacked-on'))
     safe_open(scheme, get_chrooted_url('stacked'))
Ejemplo n.º 20
0
    def run(self, _check_transaction=False):
        """See `IBranchUpgradeJob`."""
        # Set up the new branch structure
        with server(get_rw_server(), no_replace=True):
            upgrade_branch_path = tempfile.mkdtemp()
            try:
                upgrade_transport = get_transport(upgrade_branch_path)
                upgrade_transport.mkdir('.bzr')
                source_branch_transport = get_transport(
                    self.branch.getInternalBzrUrl())
                source_branch_transport.clone('.bzr').copy_tree_to_transport(
                    upgrade_transport.clone('.bzr'))
                transaction.commit()
                upgrade_branch = BzrBranch.open_from_transport(
                    upgrade_transport)

                # No transactions are open so the DB connection won't be
                # killed.
                with TransactionFreeOperation():
                    # Perform the upgrade.
                    upgrade(upgrade_branch.base)

                # Re-open the branch, since its format has changed.
                upgrade_branch = BzrBranch.open_from_transport(
                    upgrade_transport)
                source_branch = BzrBranch.open_from_transport(
                    source_branch_transport)

                source_branch.lock_write()
                upgrade_branch.pull(source_branch)
                upgrade_branch.fetch(source_branch)
                source_branch.unlock()

                # Move the branch in the old format to backup.bzr
                try:
                    source_branch_transport.delete_tree('backup.bzr')
                except NoSuchFile:
                    pass
                source_branch_transport.rename('.bzr', 'backup.bzr')
                source_branch_transport.mkdir('.bzr')
                upgrade_transport.clone('.bzr').copy_tree_to_transport(
                    source_branch_transport.clone('.bzr'))

                # Re-open the source branch again.
                source_branch = BzrBranch.open_from_transport(
                    source_branch_transport)

                formats = get_branch_formats(source_branch)

                self.branch.branchChanged(
                    self.branch.stacked_on,
                    self.branch.last_scanned_id,
                    *formats)
            finally:
                shutil.rmtree(upgrade_branch_path)
Ejemplo n.º 21
0
    def run(self, _check_transaction=False):
        """See `IBranchUpgradeJob`."""
        # Set up the new branch structure
        with server(get_rw_server(), no_replace=True):
            upgrade_branch_path = tempfile.mkdtemp()
            try:
                upgrade_transport = get_transport(upgrade_branch_path)
                upgrade_transport.mkdir('.bzr')
                source_branch_transport = get_transport(
                    self.branch.getInternalBzrUrl())
                source_branch_transport.clone('.bzr').copy_tree_to_transport(
                    upgrade_transport.clone('.bzr'))
                transaction.commit()
                upgrade_branch = BzrBranch.open_from_transport(
                    upgrade_transport)

                # No transactions are open so the DB connection won't be
                # killed.
                with TransactionFreeOperation():
                    # Perform the upgrade.
                    upgrade(upgrade_branch.base)

                # Re-open the branch, since its format has changed.
                upgrade_branch = BzrBranch.open_from_transport(
                    upgrade_transport)
                source_branch = BzrBranch.open_from_transport(
                    source_branch_transport)

                source_branch.lock_write()
                upgrade_branch.pull(source_branch)
                upgrade_branch.fetch(source_branch)
                source_branch.unlock()

                # Move the branch in the old format to backup.bzr
                try:
                    source_branch_transport.delete_tree('backup.bzr')
                except NoSuchFile:
                    pass
                source_branch_transport.rename('.bzr', 'backup.bzr')
                source_branch_transport.mkdir('.bzr')
                upgrade_transport.clone('.bzr').copy_tree_to_transport(
                    source_branch_transport.clone('.bzr'))

                # Re-open the source branch again.
                source_branch = BzrBranch.open_from_transport(
                    source_branch_transport)

                formats = get_branch_formats(source_branch)

                self.branch.branchChanged(
                    self.branch.stacked_on,
                    self.branch.last_scanned_id,
                    *formats)
            finally:
                shutil.rmtree(upgrade_branch_path)
Ejemplo n.º 22
0
 def test_open_containing(self):
     self.assertRaises(NotBranchError, Branch.open_containing,
                       self.get_readonly_url(''))
     self.assertRaises(NotBranchError, Branch.open_containing,
                       self.get_readonly_url('g/p/q'))
     branch = self.make_branch('.')
     branch, relpath = Branch.open_containing(self.get_readonly_url(''))
     self.assertEqual('', relpath)
     branch, relpath = Branch.open_containing(
         self.get_readonly_url('g/p/q'))
     self.assertEqual('g/p/q', relpath)
Ejemplo n.º 23
0
 def test_stacked_outside_scheme(self):
     # A branch that is stacked on a URL that is not of the same scheme is
     # not safe to open.
     self.get_transport().mkdir('inside')
     self.get_transport().mkdir('outside')
     self.make_branch('inside/stacked')
     self.make_branch('outside/stacked-on')
     scheme, get_chrooted_url = self.get_chrooted_scheme('inside')
     Branch.open(get_chrooted_url('stacked')).set_stacked_on_url(
         self.get_url('outside/stacked-on'))
     self.assertRaises(
         BadUrl, safe_open, scheme, get_chrooted_url('stacked'))
Ejemplo n.º 24
0
def find_branches(directory):
    """List the directory names in 'directory' that are branches."""
    branches = []
    for name in os.listdir(directory):
        if name in ('.', '..'):
            continue
        try:
            Branch.open(os.path.join(directory, name))
            branches.append(name)
        except NotBranchError:
            pass
    return branches
Ejemplo n.º 25
0
 def test_denyingServer(self):
     # DenyingServer prevents creations of transports for the given URL
     # schemes between setUp() and tearDown().
     branch = self.make_branch('branch')
     self.assertTrue(branch.base.startswith('file://'),
                     "make_branch() didn't make branch with file:// URL")
     file_denier = DenyingServer(['file://'])
     file_denier.start_server()
     self.assertRaises(AssertionError, Branch.open, branch.base)
     file_denier.stop_server()
     # This is just "assertNotRaises":
     Branch.open(branch.base)
Ejemplo n.º 26
0
 def test_stacked_outside_scheme(self):
     # A branch that is stacked on a URL that is not of the same scheme is
     # not safe to open.
     self.get_transport().mkdir('inside')
     self.get_transport().mkdir('outside')
     self.make_branch('inside/stacked')
     self.make_branch('outside/stacked-on')
     scheme, get_chrooted_url = self.get_chrooted_scheme('inside')
     Branch.open(get_chrooted_url('stacked')).set_stacked_on_url(
         self.get_url('outside/stacked-on'))
     self.assertRaises(BadUrl, safe_open, scheme,
                       get_chrooted_url('stacked'))
Ejemplo n.º 27
0
def find_branches(directory):
    """List the directory names in 'directory' that are branches."""
    branches = []
    for name in os.listdir(directory):
        if name in ('.', '..'):
            continue
        try:
            Branch.open(os.path.join(directory, name))
            branches.append(name)
        except NotBranchError:
            pass
    return branches
Ejemplo n.º 28
0
 def test_denyingServer(self):
     # DenyingServer prevents creations of transports for the given URL
     # schemes between setUp() and tearDown().
     branch = self.make_branch('branch')
     self.assertTrue(
         branch.base.startswith('file://'),
         "make_branch() didn't make branch with file:// URL")
     file_denier = DenyingServer(['file://'])
     file_denier.start_server()
     self.assertRaises(AssertionError, Branch.open, branch.base)
     file_denier.stop_server()
     # This is just "assertNotRaises":
     Branch.open(branch.base)
Ejemplo n.º 29
0
 def test_merge_fetches_file_history(self):
     """Merge brings across file histories"""
     br2 = Branch.open('br2')
     br1 = Branch.open('br1')
     wt2 = WorkingTree.open('br2').merge_from_branch(br1)
     br2.lock_read()
     self.addCleanup(br2.unlock)
     for rev_id, text in [('1-2', 'original from 1\n'),
                          ('1-3', 'agreement\n'),
                          ('2-1', 'contents in 2\n'),
                          ('2-2', 'agreement\n')]:
         self.assertEqualDiff(
             br2.repository.revision_tree(
                 rev_id).get_file_text('this-file-id'), text)
Ejemplo n.º 30
0
 def test_merge_fetches_file_history(self):
     """Merge brings across file histories"""
     br2 = Branch.open('br2')
     br1 = Branch.open('br1')
     wt2 = WorkingTree.open('br2').merge_from_branch(br1)
     br2.lock_read()
     self.addCleanup(br2.unlock)
     for rev_id, text in [('1-2', 'original from 1\n'),
                          ('1-3', 'agreement\n'),
                          ('2-1', 'contents in 2\n'),
                          ('2-2', 'agreement\n')]:
         self.assertEqualDiff(
             br2.repository.revision_tree(rev_id).get_file_text(
                 'this-file-id'), text)
Ejemplo n.º 31
0
 def test_checkOneBranch_new_stacked(self):
     # checkOneBranch returns False when the bzr branch for the database
     # branch in new distroseries is stacked.
     db_branch = self.makeOfficialPackageBranch()
     b, _ = self.create_branch_and_tree(self.factory.getUniqueString())
     brancher = self.makeNewSeriesAndBrancher(db_branch.distroseries)
     new_db_branch = brancher.makeOneNewBranch(db_branch)
     url = "lp-internal:///" + new_db_branch.unique_name
     Branch.open(url).set_stacked_on_url("/" + b.unique_name)
     ok = brancher.checkOneBranch(db_branch)
     self.assertFalse(ok)
     self.assertLogMessages(
         ["^WARNING New branch at lp-internal:///.*/.*/.*/.* is stacked on " "/.*/.*/.*, should be unstacked.$"]
     )
Ejemplo n.º 32
0
    def test_push_redirects_on_mkdir(self):
        """If the push requires a mkdir, push respects redirect requests.

        This is added primarily to handle lp:/ URI support, so that users can
        push to new branches by specifying lp:/ URIs.
        """
        os.chdir('tree')
        destination_url = self.memory_server.get_url() + 'source'
        self.run_bzr('push %s' % destination_url)
        os.chdir('..')

        local_revision = Branch.open('tree').last_revision()
        remote_revision = Branch.open(
            self.memory_server.get_url() + 'target').last_revision()
        self.assertEqual(remote_revision, local_revision)
Ejemplo n.º 33
0
 def test_checkOneBranch_new_stacked(self):
     # checkOneBranch returns False when the bzr branch for the database
     # branch in new distroseries is stacked.
     db_branch = self.makeOfficialPackageBranch()
     b, _ = self.create_branch_and_tree(self.factory.getUniqueString())
     brancher = self.makeNewSeriesAndBrancher(db_branch.distroseries)
     new_db_branch = brancher.makeOneNewBranch(db_branch)
     url = 'lp-internal:///' + new_db_branch.unique_name
     Branch.open(url).set_stacked_on_url('/' + b.unique_name)
     ok = brancher.checkOneBranch(db_branch)
     self.assertFalse(ok)
     self.assertLogMessages([
         '^WARNING New branch at lp-internal:///.*/.*/.*/.* is stacked on '
         '/.*/.*/.*, should be unstacked.$',
     ])
Ejemplo n.º 34
0
    def test_push_redirects_on_mkdir(self):
        """If the push requires a mkdir, push respects redirect requests.

        This is added primarily to handle lp:/ URI support, so that users can
        push to new branches by specifying lp:/ URIs.
        """
        os.chdir('tree')
        destination_url = self.memory_server.get_url() + 'source'
        self.run_bzr('push %s' % destination_url)
        os.chdir('..')

        local_revision = Branch.open('tree').last_revision()
        remote_revision = Branch.open(self.memory_server.get_url() +
                                      'target').last_revision()
        self.assertEqual(remote_revision, local_revision)
Ejemplo n.º 35
0
 def _on_checkout_clicked(self, button):
     """ Checkout button clicked handler. """
     location = self._combo.get_child().get_text()
     if location is '':
         error_dialog(_i18n('Missing branch location'),
                      _i18n('You must specify a branch location.'))
         return
     
     destination = self._filechooser.get_filename()
     try:
         revno = int(self._entry_revision.get_text())
     except:
         revno = None
     
     nick = self._entry_nick.get_text()
     if nick is '':
         nick = os.path.basename(location.rstrip("/\\"))
     
     br_from = Branch.open(location)
     
     revision_id = br_from.get_rev_id(revno)
     lightweight = self._check_lightweight.get_active()
     to_location = destination + os.sep + nick
     
     os.mkdir(to_location)
     
     br_from.create_checkout(to_location, revision_id, lightweight)
     
     self._history.add_entry(location)
     
     self.response(gtk.RESPONSE_OK)
Ejemplo n.º 36
0
    def _find_revision_id(branch, other_location):
        from bzrlib.branch import Branch

        branch.lock_read()
        try:
            revision_a = revision.ensure_null(branch.last_revision())
            if revision_a == revision.NULL_REVISION:
                raise errors.NoCommits(branch)
            if other_location == '':
                other_location = branch.get_parent()
            other_branch = Branch.open(other_location)
            other_branch.lock_read()
            try:
                revision_b = revision.ensure_null(other_branch.last_revision())
                if revision_b == revision.NULL_REVISION:
                    raise errors.NoCommits(other_branch)
                graph = branch.repository.get_graph(other_branch.repository)
                rev_id = graph.find_unique_lca(revision_a, revision_b)
            finally:
                other_branch.unlock()
            if rev_id == revision.NULL_REVISION:
                raise errors.NoCommonAncestor(revision_a, revision_b)
            return rev_id
        finally:
            branch.unlock()
Ejemplo n.º 37
0
 def test_range_open_end(self):
     # commit mainline rev 2
     self.make_file('hello', '42')
     self.run_bzr('commit -m that')
     # commit feature rev 2
     os.chdir('../feature')
     self.make_file('hoi', "my data")
     self.run_bzr('add')
     self.run_bzr('commit -m this')
     # commit feature rev 3
     self.make_file('hooi', "your data")
     self.run_bzr('add')
     self.run_bzr('commit -m that')
     # commit feature rev 4
     self.make_file('hoooi', "someone else's data")
     self.run_bzr('add')
     self.run_bzr('commit -m these')
     # rebase only rev 4 onto main
     self.assertEquals('', self.run_bzr('rebase -r4.. ../main')[0])
     # should only get rev 3 (our old 2 and 3 are gone)
     self.assertEquals('3\n', self.run_bzr('revno')[0])
     self.assertPathDoesNotExist('hoi')
     self.assertPathDoesNotExist('hooi')
     branch = Branch.open(".")
     self.assertEquals("these",
         branch.repository.get_revision(branch.last_revision()).message)
     self.assertPathExists('hoooi')
Ejemplo n.º 38
0
def bzr_branch(ROOT,
               remote_branches,
               cmd='',
               branch=False):  #for existing branches, cmd can be push or pull
    out = []
    for rb, local in remote_branches:
        #l=os.path.join(ROOT, *rb.split('/')[-2:] )
        #p=os.path.join(ROOT, *rb.split('/')[-2:-1] ) #parent path
        l, p = bzr_remote2local(ROOT, local)
        out.append(l)
        if os.path.isdir(l):
            #print 'exist'
            pass
            #if cmd in ['pull','push']:
            #    r=Branch.open(rb) #remote branch
            #    b=Branch.open(l)  #local branch
            #    if cmd=='pull':
            #        b.pull(r)
            #    if cmd=='push':
            #        b.push(r)
        else:
            if branch:
                if not os.path.isdir(p):
                    os.makedirs(p)  #create if it does not exist
                #print 'does not exist',  [rb, p, l]
                r = Branch.open(rb)  #remote branch
                new = r.bzrdir.sprout(l)  #new loca branch
    return out
Ejemplo n.º 39
0
Archivo: pull.py Proyecto: biji/qbzr
    def _suggested_push_location(self):
        """Suggest a push location when one is not already defined.

        @return: a sensible location as a string or '' if none.
        """
        # If this is a feature branch and its parent exists locally,
        # its grandparent is likely to be the hosted master branch.
        # If so, suggest a push location, otherwise don't.
        parent_url = self.branch.get_parent()
        if parent_url and parent_url.startswith("file://"):
            from bzrlib.branch import Branch
            try:
                parent_branch = Branch.open(parent_url)
            except errors.NotBranchError:
                return ''
            master_url = (parent_branch.get_parent()
                          or parent_branch.get_bound_location())
            if master_url and not master_url.startswith("file://"):
                if master_url.find("launchpad") >= 0:
                    suggest_url = self._build_lp_push_suggestion(master_url)
                    if suggest_url:
                        return suggest_url
                # XXX we can hook in there even more specific suggesters
                # XXX maybe we need registry?
                suggest_url = self._build_generic_push_suggestion(master_url)
                if suggest_url:
                    return suggest_url
        return ''
Ejemplo n.º 40
0
    def test_bind_parent_ahead_preserves_parent(self):
        b_base, wt_child = self.create_branches()

        wt_child.branch.unbind()

        open('a', 'ab').write('base changes\n')
        wt_base = b_base.bzrdir.open_workingtree()
        wt_base.commit('base', rev_id='r@b-2')
        self.assertEqual(['r@b-1', 'r@b-2'], b_base.revision_history())
        self.assertEqual(['r@b-1'], wt_child.branch.revision_history())

        sftp_b_base = Branch.open(self.get_url('base'))
        wt_child.branch.bind(sftp_b_base)

        self.assertEqual(['r@b-1'], wt_child.branch.revision_history())

        wt_child.branch.unbind()

        # Check and make sure it also works if parent is ahead multiple
        wt_base.commit('base 3', rev_id='r@b-3', allow_pointless=True)
        wt_base.commit('base 4', rev_id='r@b-4', allow_pointless=True)
        wt_base.commit('base 5', rev_id='r@b-5', allow_pointless=True)

        self.assertEqual(['r@b-1', 'r@b-2', 'r@b-3', 'r@b-4', 'r@b-5'],
                         b_base.revision_history())

        self.assertEqual(['r@b-1'], wt_child.branch.revision_history())

        wt_child.branch.bind(sftp_b_base)
        self.assertEqual(['r@b-1'], wt_child.branch.revision_history())
Ejemplo n.º 41
0
    def test_unbinding(self):
        from bzrlib.transport import get_transport
        b_base, wt_child = self.create_branches()

        # TestCaseWithSFTPServer only allows you to connect one time
        # to the SFTP server. So we have to create a connection and
        # keep it around, so that it can be reused
        __unused_t = get_transport(self.get_url('.'))

        wt_base = b_base.bzrdir.open_workingtree()
        open('base/a', 'wb').write('new base contents\n')
        wt_base.commit('base', rev_id='r@b-2')

        open('child/b', 'wb').write('new b child contents\n')
        self.assertRaises(errors.BoundBranchOutOfDate,
                          wt_child.commit,
                          'child',
                          rev_id='r@c-2')
        self.assertEqual(['r@b-1'], wt_child.branch.revision_history())
        wt_child.branch.unbind()
        wt_child.commit('child', rev_id='r@c-2')
        self.assertEqual(['r@b-1', 'r@c-2'],
                         wt_child.branch.revision_history())
        self.assertEqual(['r@b-1', 'r@b-2'], b_base.revision_history())

        sftp_b_base = Branch.open(self.get_url('base'))
        self.assertRaises(errors.DivergedBranches, wt_child.branch.bind,
                          sftp_b_base)
Ejemplo n.º 42
0
def bundle(dir):
    branch = Branch.open(dir)
    output_zip = '%s_%d.zip'%(dir, branch.revno())
    temp_dir = '/tmp/output_%d'%(branch.revno())

    #Empty the temp_dir
    shutil.rmtree(temp_dir, True)

    #export the bzr repository to temp_dir
    export(branch.basis_tree(), temp_dir)

    #Compile the source code in templocation
    compileall.compile_dir(temp_dir)

    #Remove the .py files from the exported directory.
    clean_path(temp_dir, [".py"])
    
    #create a HISTORY file in the temp_dir
    show_log(branch, ShortLogFormatter(open(temp_dir+os.sep+'HISTORY', 'w')))

    #create a VERSION file in temp_dir
    f = open(temp_dir+os.sep+'VERSION', 'w')
    f.write(str(branch.revno()))
    f.close()

    #write to zip
    z.toZip(temp_dir, output_zip)
Ejemplo n.º 43
0
Archivo: bzr.py Proyecto: Etenil/anvil
def _get_branch_file(path, fileid):
    b = Branch.open(path)
    t = b.basis_tree()
    b.lock_read()
    f = (t.id2path(fileid), t.get_file_text(fileid))
    b.unlock()
    return f
Ejemplo n.º 44
0
def get_branches(sourcecode_directory, new_branches,
                 possible_transports=None, tip=False, quiet=False):
    """Get the new branches into sourcecode."""
    for project, (branch_url, revision, optional) in new_branches.iteritems():
        destination = os.path.join(sourcecode_directory, project)
        try:
            remote_branch = Branch.open(
                branch_url, possible_transports=possible_transports)
        except BzrError:
            if optional:
                report_exception(sys.exc_info(), sys.stderr)
                continue
            else:
                raise
        possible_transports.append(
            remote_branch.bzrdir.root_transport)
        if not quiet:
            print 'Getting %s from %s at %s' % (
                    project, branch_url, _format_revision_name(revision, tip))
        # If the 'optional' flag is set, then it's a branch that shares
        # history with Launchpad, so we should share repositories. Otherwise,
        # we should avoid sharing repositories to avoid format
        # incompatibilities.
        force_new_repo = not optional
        revision_id = get_revision_id(revision, remote_branch, tip)
        remote_branch.bzrdir.sprout(
            destination, revision_id=revision_id, create_tree_if_local=True,
            source_branch=remote_branch, force_new_repo=force_new_repo,
            possible_transports=possible_transports)
Ejemplo n.º 45
0
    def export(self, target):
        self.log.debug('Exporting %s to %s' % (self.source, target))

        # Check branch
        remote = Branch.open(self.source)

        # Get revision id
        revinfo = None
        revid = None
        if self.revision is not None:
            revid = remote.get_rev_id(self.revision)
            revinfo = 'rev: %s' % self.revision
        elif self.tag is not None:
            revid = remote.tags.lookup_tag(self.tag)
            revinfo = 'tag: %s' % self.tag
        else:
            revid = remote.last_revision()
            revinfo = 'last'

        # Get tree
        tree = remote.repository.revision_tree(revid)

        # Export tree
        self.log.debug('Downloading bazaar tree: %s (%s)' % (self.source, revinfo))
        bzrlib.export.export(tree, target, None)
Ejemplo n.º 46
0
    def _find_revision_id(branch, other_location):
        from bzrlib.branch import Branch

        branch.lock_read()
        try:
            revision_a = revision.ensure_null(branch.last_revision())
            if revision_a == revision.NULL_REVISION:
                raise errors.NoCommits(branch)
            if other_location == '':
                other_location = branch.get_parent()
            other_branch = Branch.open(other_location)
            other_branch.lock_read()
            try:
                revision_b = revision.ensure_null(other_branch.last_revision())
                if revision_b == revision.NULL_REVISION:
                    raise errors.NoCommits(other_branch)
                graph = branch.repository.get_graph(other_branch.repository)
                rev_id = graph.find_unique_lca(revision_a, revision_b)
            finally:
                other_branch.unlock()
            if rev_id == revision.NULL_REVISION:
                raise errors.NoCommonAncestor(revision_a, revision_b)
            return rev_id
        finally:
            branch.unlock()
    def test_upgrade_branches_packagebranch(self):
        """Test that upgrade_branches can upgrade package branches."""
        self.useBzrBranches()
        package_branch = self.factory.makePackageBranch()
        target, target_tree = self.create_branch_and_tree(
            db_branch=package_branch, format='knit')
        target.branch_format = BranchFormat.BZR_BRANCH_5
        target.repository_format = RepositoryFormat.BZR_KNIT_1

        self.assertEqual(
            target_tree.branch.repository._format.get_format_string(),
            'Bazaar-NG Knit Repository Format 1')

        BranchUpgradeJob.create(target, self.factory.makePerson())
        transaction.commit()

        retcode, stdout, stderr = run_script(
            'cronscripts/process-job-source.py', ['IBranchUpgradeJobSource'],
            expect_returncode=0)
        self.assertEqual('', stdout)
        self.assertIn(
            'INFO    Ran 1 BranchUpgradeJob jobs.\n', stderr)

        target_branch = BzrBranch.open(target_tree.branch.base)
        self.assertEqual(
            target_branch.repository._format.get_format_string(),
            'Bazaar repository format 2a (needs bzr 1.16 or later)\n')
Ejemplo n.º 48
0
  def run(self):
    self.gladefile = gladeFile().filename
    #self.wTree = gtk.glade.XML(self.gladefile, "whatsNewDialog")
    self.wTree = gtk.Builder()
    self.wTree.add_objects_from_file(self.gladefile, ["whatsNewDialog"])
    self.dlg = self.wTree.get_object("whatsNewDialog")
    self.textView = self.wTree.get_object('whatsNewDialogTextView')
    buffer = gtk.TextBuffer()
    self.textView.set_buffer(buffer)
    
    try:
      from bzrlib.branch import Branch
      my_branch = Branch.open(os.path.join(os.path.dirname(__file__), '../..'))
      rev_ids = my_branch.revision_history()
      rev_ids.reverse()
      repo = my_branch.repository
      for rev_id in rev_ids:
        revision=repo.get_revision(rev_id)
        buffer.insert_at_cursor('revision ')
        buffer.insert_at_cursor(str(my_branch.revision_id_to_revno(rev_id)))
        buffer.insert_at_cursor(' :: ')
        buffer.insert_at_cursor(revision.message)
        buffer.insert_at_cursor('\n\n')
    except:
      pass

    self.result = self.dlg.run()
    self.dlg.destroy()
def main(directory, force=False):
    WebServiceApplication.cached_wadl = None  # do not use cached file version
    execute_zcml_for_scripts()
    config = getUtility(IWebServiceConfiguration)

    # First, create an index.html with links to all the HTML
    # documentation files we're about to generate.
    template_file = "apidoc-index.pt"
    template = PageTemplateFile(template_file)
    index_filename = os.path.join(directory, "index.html")
    print "Writing index:", index_filename
    f = open(index_filename, "w")
    f.write(template(config=config))

    # Get the time of the last commit.  We will use this as the mtime for the
    # generated files so that we can safely use it as part of Apache's etag
    # generation in the face of multiple servers/filesystems.
    with bzrlib.initialize():
        branch = Branch.open(os.path.dirname(os.path.dirname(__file__)))
        timestamp = branch.repository.get_revision(branch.last_revision()).timestamp

    # Start a process to build each set of WADL and HTML files.
    processes = []
    for version in config.active_versions:
        p = Process(target=make_files, args=(directory, version, timestamp, force))
        p.start()
        processes.append(p)

    # Wait for all the subprocesses to finish.
    for p in processes:
        p.join()

    return 0
Ejemplo n.º 50
0
    def test_bound_commit_fails_when_out_of_date(self):
        # Make sure commit fails if out of date.
        b_base, wt_child = self.create_branches()

        open('base/a', 'wb').write('new base contents\n')
        b_base.bzrdir.open_workingtree().commit('base', rev_id='r@b-2')

        open('child/b', 'wb').write('new b child contents\n')
        self.assertRaises(errors.BoundBranchOutOfDate,
                          wt_child.commit,
                          'child',
                          rev_id='r@c-2')

        sftp_b_base = Branch.open(self.get_url('base'))

        # This is all that cmd_update does
        wt_child.pull(sftp_b_base, overwrite=False)

        wt_child.commit('child', rev_id='r@c-3')

        self.assertEqual(['r@b-1', 'r@b-2', 'r@c-3'],
                         wt_child.branch.revision_history())
        self.assertEqual(['r@b-1', 'r@b-2', 'r@c-3'],
                         b_base.revision_history())
        self.assertEqual(['r@b-1', 'r@b-2', 'r@c-3'],
                         sftp_b_base.revision_history())
Ejemplo n.º 51
0
    def run(self):
        self.gladefile = gladeFile().filename
        #self.wTree = gtk.glade.XML(self.gladefile, "whatsNewDialog")
        self.wTree = gtk.Builder()
        self.wTree.add_objects_from_file(self.gladefile, ["whatsNewDialog"])
        self.dlg = self.wTree.get_object("whatsNewDialog")
        self.textView = self.wTree.get_object('whatsNewDialogTextView')
        buffer = gtk.TextBuffer()
        self.textView.set_buffer(buffer)

        try:
            from bzrlib.branch import Branch
            my_branch = Branch.open(
                os.path.join(os.path.dirname(__file__), '../..'))
            rev_ids = my_branch.revision_history()
            rev_ids.reverse()
            repo = my_branch.repository
            for rev_id in rev_ids:
                revision = repo.get_revision(rev_id)
                buffer.insert_at_cursor('revision ')
                buffer.insert_at_cursor(
                    str(my_branch.revision_id_to_revno(rev_id)))
                buffer.insert_at_cursor(' :: ')
                buffer.insert_at_cursor(revision.message)
                buffer.insert_at_cursor('\n\n')
        except:
            pass

        self.result = self.dlg.run()
        self.dlg.destroy()
Ejemplo n.º 52
0
    def test_bind_diverged(self):
        b_base, wt_child = self.create_branches()

        wt_child.branch.unbind()
        open('child/a', 'ab').write('child contents\n')
        wt_child_rev = wt_child.commit('child', rev_id='r@c-2')

        self.assertEqual(['r@b-1', 'r@c-2'],
                         wt_child.branch.revision_history())
        self.assertEqual(['r@b-1'], b_base.revision_history())

        open('base/b', 'ab').write('base contents\n')
        b_base.bzrdir.open_workingtree().commit('base', rev_id='r@b-2')
        self.assertEqual(['r@b-1', 'r@b-2'], b_base.revision_history())

        sftp_b_base = Branch.open(self.get_url('base'))

        self.assertRaises(errors.DivergedBranches, wt_child.branch.bind,
                          sftp_b_base)

        wt_child.merge_from_branch(sftp_b_base)
        self.assertEqual([wt_child_rev, 'r@b-2'], wt_child.get_parent_ids())
        wt_child.commit('merged', rev_id='r@c-3')

        # After a merge, trying to bind again should succeed but not push the
        # new change.
        wt_child.branch.bind(sftp_b_base)

        self.assertEqual(['r@b-1', 'r@b-2'], b_base.revision_history())
        self.assertEqual(['r@b-1', 'r@c-2', 'r@c-3'],
                         wt_child.branch.revision_history())
Ejemplo n.º 53
0
    def test_last_revision_is_null(self):
        tests.run_git('init')

        thebranch = Branch.open('.')
        self.assertEqual(revision.NULL_REVISION, thebranch.last_revision())
        self.assertEqual((0, revision.NULL_REVISION),
                         thebranch.last_revision_info())
Ejemplo n.º 54
0
    def test_bind_child_ahead_preserves_child(self):
        b_base, wt_child = self.create_branches()

        wt_child.branch.unbind()

        wt_child.commit('child', rev_id='r@c-2', allow_pointless=True)
        self.assertEqual(['r@b-1', 'r@c-2'],
                         wt_child.branch.revision_history())
        self.assertEqual(['r@b-1'], b_base.revision_history())

        sftp_b_base = Branch.open(self.get_url('base'))
        wt_child.branch.bind(sftp_b_base)

        self.assertEqual(['r@b-1'], b_base.revision_history())

        # Check and make sure it also works if child is ahead multiple
        wt_child.branch.unbind()
        wt_child.commit('child 3', rev_id='r@c-3', allow_pointless=True)
        wt_child.commit('child 4', rev_id='r@c-4', allow_pointless=True)
        wt_child.commit('child 5', rev_id='r@c-5', allow_pointless=True)

        self.assertEqual(['r@b-1', 'r@c-2', 'r@c-3', 'r@c-4', 'r@c-5'],
                         wt_child.branch.revision_history())
        self.assertEqual(['r@b-1'], b_base.revision_history())

        wt_child.branch.bind(sftp_b_base)
        self.assertEqual(['r@b-1'], b_base.revision_history())
Ejemplo n.º 55
0
def get_branches(sourcecode_directory,
                 new_branches,
                 possible_transports=None,
                 tip=False,
                 quiet=False):
    """Get the new branches into sourcecode."""
    for project, (branch_url, revision, optional) in new_branches.iteritems():
        destination = os.path.join(sourcecode_directory, project)
        try:
            remote_branch = Branch.open(
                branch_url, possible_transports=possible_transports)
        except BzrError:
            if optional:
                report_exception(sys.exc_info(), sys.stderr)
                continue
            else:
                raise
        possible_transports.append(remote_branch.bzrdir.root_transport)
        if not quiet:
            print 'Getting %s from %s at %s' % (
                project, branch_url, _format_revision_name(revision, tip))
        # If the 'optional' flag is set, then it's a branch that shares
        # history with Launchpad, so we should share repositories. Otherwise,
        # we should avoid sharing repositories to avoid format
        # incompatibilities.
        force_new_repo = not optional
        revision_id = get_revision_id(revision, remote_branch, tip)
        remote_branch.bzrdir.sprout(destination,
                                    revision_id=revision_id,
                                    create_tree_if_local=True,
                                    source_branch=remote_branch,
                                    force_new_repo=force_new_repo,
                                    possible_transports=possible_transports)
Ejemplo n.º 56
0
 def _repository(self):
     if self.__repository is None:
         try:
             self.__repository = Branch.open(self.url)
         except Exception as err:
             raise VersionControlError("Cannot access Bazaar repository at %s: %s" % (self.url, err))
     return self.__repository
Ejemplo n.º 57
0
 def assertPublished(self, branch_revid, stacked_on):
     """Assert that the branch 'published' has been published correctly."""
     published_branch = Branch.open('published')
     # The published branch refers to the mainline
     self.assertEqual(stacked_on, published_branch.get_stacked_on_url())
     # and the branch's work was pushed
     self.assertTrue(published_branch.repository.has_revision(branch_revid))
Ejemplo n.º 58
0
    def test_last_revision_is_valid(self):
        self.simple_commit_a()
        head = tests.run_git('rev-parse', 'HEAD').strip()

        thebranch = Branch.open('.')
        self.assertEqual(default_mapping.revision_id_foreign_to_bzr(head),
                         thebranch.last_revision())
Ejemplo n.º 59
0
    def createDestinationBranch(self, source_branch, destination_url):
        """Create a destination branch for 'source_branch'.

        Creates a branch at 'destination_url' that is has the same format as
        'source_branch'.  Any content already at 'destination_url' will be
        deleted.  Generally the new branch will have no revisions, but they
        will be copied for import branches, because this can be done safely
        and efficiently with a vfs-level copy (see `ImportedBranchPolicy`).

        :param source_branch: The Bazaar branch that will be mirrored.
        :param destination_url: The place to make the destination branch. This
            URL must point to a writable location.
        :return: The destination branch.
        """
        dest_transport = get_transport(destination_url)
        if dest_transport.has('.'):
            dest_transport.delete_tree('.')
        if isinstance(source_branch, LoomSupport):
            # Looms suck.
            revision_id = None
        else:
            revision_id = 'null:'
        source_branch.bzrdir.clone_on_transport(
            dest_transport, revision_id=revision_id)
        return Branch.open(destination_url)