Ejemplo n.º 1
0
    def run(self, destination=None, remember=False, overwrite=False):
        from repopush import repo_push

        # get the repository for the branch we're currently in
        bzrdir = BzrDir.open_containing('.')[0]
        try:
            branch = bzrdir.open_branch()
            src_repo = branch.repository
        except errors.NotBranchError:
            src_repo = bzrdir.open_repository()
        repo_config = LocationConfig(src_repo.bzrdir.root_transport.base)

        if destination is None:
            destination = repo_config.get_user_option('public_repository')
            if destination is None:
                raise errors.BzrCommandError('No destination specified')

        dst_repo = BzrDir.open(destination).open_repository()

        if remember or (repo_config.get_user_option('public_repository') is
                        None):
            repo_config.set_user_option('public_repository',
                                        dst_repo.bzrdir.root_transport.base)

        pb = ui_factory.nested_progress_bar()
        try:
            repo_push(src_repo, dst_repo, pb=pb, overwrite=overwrite)
        finally:
            pb.finished()
Ejemplo n.º 2
0
    def run(self, src_location, dest_location):
        from bzrlib.bzrdir import BzrDir, format_registry
        from bzrlib.errors import NoRepositoryPresent, NotBranchError
        from bzrlib.repository import Repository
        source_repo = Repository.open(src_location)
        format = format_registry.make_bzrdir('rich-root-pack')
        try:
            target_bzrdir = BzrDir.open(dest_location)
        except NotBranchError:
            target_bzrdir = BzrDir.create(dest_location, format=format)
        try:
            target_repo = target_bzrdir.open_repository()
        except NoRepositoryPresent:
            target_repo = target_bzrdir.create_repository(shared=True)

        target_repo.fetch(source_repo)
        for name, ref in source_repo._git.heads().iteritems():
            head_loc = os.path.join(dest_location, name)
            try:
                head_bzrdir = BzrDir.open(head_loc)
            except NotBranchError:
                head_bzrdir = BzrDir.create(head_loc, format=format)
            try:
                head_branch = head_bzrdir.open_branch()
            except NotBranchError:
                head_branch = head_bzrdir.create_branch()
            head_branch.generate_revision_history(source_repo.get_mapping().revision_id_foreign_to_bzr(ref))
Ejemplo n.º 3
0
def get_branch(repo, relpath, format=None):
    """Return existing branch in destination repo. Create new if don't exist.

    @param  format:     force create new branch in specified format.
    """
    repo_trans = repo.bzrdir.root_transport
    try:
        br_dir = BzrDir.open(repo_trans.abspath(relpath))
        branch = br_dir.open_branch()
    except errors.NotBranchError:
        # create destination branch directory, creating parents as needed.
        needed = [relpath]
        while needed:
            try:
                repo_trans.mkdir(needed[-1])
                needed.pop()
            except errors.NoSuchFile:
                parent = urlutils.dirname(needed[-1])
                if parent == '':
                    raise errors.BzrCommandError('Could not create branch dir')
                needed.append(parent)
        br_dir = BzrDir.create(repo_trans.abspath(relpath))
        if format is None:
            format = BranchFormat.get_default_format()
        branch = format.initialize(br_dir)

        note('Created destination branch %s' % relpath)

    if branch.repository.bzrdir.root_transport.base != repo_trans.base:
        raise errors.BzrCommandError('Branch %s does not use repository %s' %
                                     (relpath, repo_trans.base))
    # XXX: hack to make sure the branch is using the same repository
    # instance, for locking purposes
    branch.repository = repo
    return branch
Ejemplo n.º 4
0
 def test_shared_repos(self):
     self.make_repository('a', shared=True)
     BzrDir.create_branch_convenience('a/branch1')
     b = BzrDir.create_branch_convenience('a/branch2')
     b.create_checkout(lightweight=True, to_location='b')
     out, err = self.run_bzr('branches b')
     self.assertEqual(out, "  branch1\n" "* branch2\n")
Ejemplo n.º 5
0
    def run(self, destination=None, remember=False, overwrite=False):
        from repopush import repo_push

        # get the repository for the branch we're currently in
        bzrdir = BzrDir.open_containing('.')[0]
        try:
            branch = bzrdir.open_branch()
            src_repo = branch.repository
        except errors.NotBranchError:
            src_repo = bzrdir.open_repository()
        repo_config = LocationConfig(src_repo.bzrdir.root_transport.base)

        if destination is None:
            destination = repo_config.get_user_option('public_repository')
            if destination is None:
                raise errors.BzrCommandError('No destination specified')

        dst_repo = BzrDir.open(destination).open_repository()

        if remember or (repo_config.get_user_option('public_repository')
                        is None):
            repo_config.set_user_option('public_repository',
                                        dst_repo.bzrdir.root_transport.base)

        pb = ui_factory.nested_progress_bar()
        try:
            repo_push(src_repo, dst_repo, pb=pb, overwrite=overwrite)
        finally:
            pb.finished()
Ejemplo n.º 6
0
def get_branch(repo, relpath, format=None):
    """Return existing branch in destination repo. Create new if don't exist.

    @param  format:     force create new branch in specified format.
    """
    repo_trans = repo.bzrdir.root_transport
    try:
        br_dir = BzrDir.open(repo_trans.abspath(relpath))
        branch = br_dir.open_branch()
    except errors.NotBranchError:
        # create destination branch directory, creating parents as needed.
        needed = [relpath]
        while needed:
            try:
                repo_trans.mkdir(needed[-1])
                needed.pop()
            except errors.NoSuchFile:
                parent = urlutils.dirname(needed[-1])
                if parent == '':
                    raise errors.BzrCommandError('Could not create branch dir')
                needed.append(parent)
        br_dir = BzrDir.create(repo_trans.abspath(relpath))
        if format is None:
            format = BranchFormat.get_default_format()
        branch = format.initialize(br_dir)

        note('Created destination branch %s' % relpath)

    if branch.repository.bzrdir.root_transport.base != repo_trans.base:
        raise errors.BzrCommandError('Branch %s does not use repository %s'
                                     % (relpath, repo_trans.base))
    # XXX: hack to make sure the branch is using the same repository
    # instance, for locking purposes
    branch.repository = repo
    return branch
Ejemplo n.º 7
0
Archivo: bzr.py Proyecto: lelit/tailor
    def _checkoutUpstreamRevision(self, revision):
        """
        Initial checkout of upstream branch, equivalent of 'bzr branch -r',
        and return the last changeset.
        """

        from os.path import join, exists

        if exists(join(self.repository.basedir, '.bzr')):
            bzrdir = BzrDir.open(self.repository.basedir)
            branch = bzrdir.open_branch()
            self._working_tree = bzrdir.open_workingtree()
            revid = self._working_tree.last_revision()
            return self._changesetFromRevision(branch, revid)
        else:
            parent_bzrdir = BzrDir.open(self.repository.repository)
            parent_branch = parent_bzrdir.open_branch()

            if revision == "INITIAL":
                try:
                    revid = parent_branch.get_rev_id(1)
                except NoSuchRevision:
                    return None
            elif revision == "HEAD":
                revid = None
            else:
                revid = revision

            self.log.info('Extracting %r out of %r in %r...',
                          revid, parent_bzrdir.root_transport.base,
                          self.repository.basedir)
            bzrdir = parent_bzrdir.sprout(self.repository.basedir, revid)
            self._working_tree = bzrdir.open_workingtree()

            return self._changesetFromRevision(parent_branch, revid)
Ejemplo n.º 8
0
    def run(self, src_location, dest_location):
        from bzrlib.bzrdir import BzrDir, format_registry
        from bzrlib.errors import NoRepositoryPresent, NotBranchError
        from bzrlib.repository import Repository
        source_repo = Repository.open(src_location)
        format = format_registry.make_bzrdir('rich-root-pack')
        try:
            target_bzrdir = BzrDir.open(dest_location)
        except NotBranchError:
            target_bzrdir = BzrDir.create(dest_location, format=format)
        try:
            target_repo = target_bzrdir.open_repository()
        except NoRepositoryPresent:
            target_repo = target_bzrdir.create_repository(shared=True)

        target_repo.fetch(source_repo)
        for name, ref in source_repo._git.heads().iteritems():
            head_loc = os.path.join(dest_location, name)
            try:
                head_bzrdir = BzrDir.open(head_loc)
            except NotBranchError:
                head_bzrdir = BzrDir.create(head_loc, format=format)
            try:
                head_branch = head_bzrdir.open_branch()
            except NotBranchError:
                head_branch = head_bzrdir.create_branch()
            head_branch.generate_revision_history(
                source_repo.get_mapping().revision_id_foreign_to_bzr(ref))
Ejemplo n.º 9
0
Archivo: bzr.py Proyecto: yut148/tailor
    def _checkoutUpstreamRevision(self, revision):
        """
        Initial checkout of upstream branch, equivalent of 'bzr branch -r',
        and return the last changeset.
        """

        from os.path import join, exists

        if exists(join(self.repository.basedir, '.bzr')):
            bzrdir = BzrDir.open(self.repository.basedir)
            branch = bzrdir.open_branch()
            self._working_tree = bzrdir.open_workingtree()
            revid = self._working_tree.last_revision()
            return self._changesetFromRevision(branch, revid)
        else:
            parent_bzrdir = BzrDir.open(self.repository.repository)
            parent_branch = parent_bzrdir.open_branch()

            if revision == "INITIAL":
                try:
                    revid = parent_branch.get_rev_id(1)
                except NoSuchRevision:
                    return None
            elif revision == "HEAD":
                revid = None
            else:
                revid = revision

            self.log.info('Extracting %r out of %r in %r...', revid,
                          parent_bzrdir.root_transport.base,
                          self.repository.basedir)
            bzrdir = parent_bzrdir.sprout(self.repository.basedir, revid)
            self._working_tree = bzrdir.open_workingtree()

            return self._changesetFromRevision(parent_branch, revid)
Ejemplo n.º 10
0
    def _makeDefaultStackedOnBranch(self, private=False):
        """Make a default stacked-on branch.

        This creates a database product branch, makes it the default
        stacked-on branch for its product and creates a Bazaar branch for it.

        :param private: Whether the created branch should be private or not
            (defaults to not).
        :return: `IBranch`.
        """
        # Make the branch in the database.
        product = self.factory.makeProduct()
        if private:
            information_type = InformationType.USERDATA
        else:
            information_type = InformationType.PUBLIC
        default_branch = self.factory.makeProductBranch(
            product=product, information_type=information_type)
        transaction.commit()
        # Create the underlying bzr branch.
        lp_server = self.getLPServerForUser(default_branch.owner)
        BzrDir.create_branch_convenience(
            lp_server.get_url() + default_branch.unique_name)
        transaction.commit()
        # Make it the default stacked-on branch for the product.
        series = removeSecurityProxy(product.development_focus)
        series.branch = default_branch
        self.assertEqual(
            default_branch, IBranchTarget(product).default_stacked_on_branch)
        return default_branch
Ejemplo n.º 11
0
    def _makeDefaultStackedOnBranch(self, private=False):
        """Make a default stacked-on branch.

        This creates a database product branch, makes it the default
        stacked-on branch for its product and creates a Bazaar branch for it.

        :param private: Whether the created branch should be private or not
            (defaults to not).
        :return: `IBranch`.
        """
        # Make the branch in the database.
        product = self.factory.makeProduct()
        if private:
            information_type = InformationType.USERDATA
        else:
            information_type = InformationType.PUBLIC
        default_branch = self.factory.makeProductBranch(
            product=product, information_type=information_type)
        transaction.commit()
        # Create the underlying bzr branch.
        lp_server = self.getLPServerForUser(default_branch.owner)
        BzrDir.create_branch_convenience(
            lp_server.get_url() + default_branch.unique_name)
        transaction.commit()
        # Make it the default stacked-on branch for the product.
        series = removeSecurityProxy(product.development_focus)
        series.branch = default_branch
        self.assertEqual(
            default_branch, IBranchTarget(product).default_stacked_on_branch)
        return default_branch
Ejemplo n.º 12
0
 def test_shared_repos(self):
     self.make_repository('a', shared=True)
     BzrDir.create_branch_convenience('a/branch1')
     b = BzrDir.create_branch_convenience('a/branch2')
     b.create_checkout(lightweight=True, to_location='b')
     out, err = self.run_bzr('branches b')
     self.assertEquals(out, "  branch1\n"
                            "* branch2\n")
Ejemplo n.º 13
0
    def setUp(self):
        """Set up tests."""

        # These tests assume a branch with five revisions, and
        # a branch from version 1 containing three revisions
        # merged at version 2.

        TestCaseWithTransport.setUp(self)

        self.tree = self.make_branch_and_tree(".")

        test_file = open("test_file", "w")
        test_file.write("one")
        test_file.close()
        self.tree.add(self.tree.relpath(os.path.join(os.getcwd(),
                                                     'test_file')))
        test_file_append = open("test_file_append", "a")
        test_file_append.write("one\n")
        test_file_append.close()
        self.tree.add(self.tree.relpath(os.path.join(os.getcwd(),
                                                     'test_file_append')))
        self.tree.commit(message = "add test files")

        BzrDir.open(".").sprout("../temp-clone")
        clone_bzrdir = BzrDir.open("../temp-clone")
        clone_tree = clone_bzrdir.open_workingtree()
        for content in ["one dot one", "one dot two", "one dot three"]:
            test_file = open("../temp-clone/test_file", "w")
            test_file.write(content)
            test_file.close()
            test_file_append = open("../temp-clone/test_file_append", "a")
            test_file_append.write(content + "\n")
            test_file_append.close()
            clone_tree.commit(message = "make branch test change")
            saved_subtree_revid = clone_tree.branch.last_revision()

        self.tree.merge_from_branch(clone_tree.branch)
        test_file = open("test_file", "w")
        test_file.write("two")
        test_file.close()
        test_file_append = open("test_file_append", "a")
        test_file_append.write("two\n")
        test_file_append.close()
        self.tree.commit(message = "merge external branch")
        shutil.rmtree("../temp-clone")

        self.subtree_rev = saved_subtree_revid

        file_contents = ["three", "four", "five"]
        for content in file_contents:
            test_file = open("test_file", "w")
            test_file.write(content)
            test_file.close()
            test_file_append = open("test_file_append", "a")
            test_file_append.write(content + "\n")
            test_file_append.close()
            self.tree.commit(message = "make test change")
Ejemplo n.º 14
0
    def setUp(self):
        """Set up tests."""

        # These tests assume a branch with five revisions, and
        # a branch from version 1 containing three revisions
        # merged at version 2.

        TestCaseWithTransport.setUp(self)

        self.tree = self.make_branch_and_tree(".")

        test_file = open("test_file", "w")
        test_file.write("one")
        test_file.close()
        self.tree.add(self.tree.relpath(os.path.join(os.getcwd(),
                                                     'test_file')))
        test_file_append = open("test_file_append", "a")
        test_file_append.write("one\n")
        test_file_append.close()
        self.tree.add(
            self.tree.relpath(os.path.join(os.getcwd(), 'test_file_append')))
        self.tree.commit(message="add test files")

        BzrDir.open(".").sprout("../temp-clone")
        clone_bzrdir = BzrDir.open("../temp-clone")
        clone_tree = clone_bzrdir.open_workingtree()
        for content in ["one dot one", "one dot two", "one dot three"]:
            test_file = open("../temp-clone/test_file", "w")
            test_file.write(content)
            test_file.close()
            test_file_append = open("../temp-clone/test_file_append", "a")
            test_file_append.write(content + "\n")
            test_file_append.close()
            clone_tree.commit(message="make branch test change")
            saved_subtree_revid = clone_tree.branch.last_revision()

        self.tree.merge_from_branch(clone_tree.branch)
        test_file = open("test_file", "w")
        test_file.write("two")
        test_file.close()
        test_file_append = open("test_file_append", "a")
        test_file_append.write("two\n")
        test_file_append.close()
        self.tree.commit(message="merge external branch")
        shutil.rmtree("../temp-clone")

        self.subtree_rev = saved_subtree_revid

        file_contents = ["three", "four", "five"]
        for content in file_contents:
            test_file = open("test_file", "w")
            test_file.write(content)
            test_file.close()
            test_file_append = open("test_file_append", "a")
            test_file_append.write(content + "\n")
            test_file_append.close()
            self.tree.commit(message="make test change")
Ejemplo n.º 15
0
Archivo: repo.py Proyecto: brtsz/zato
 def ensure_repo_consistency(self):
     """ Makes sure the self.repo_location directory is a Bazaar branch.
     The repo and Bazaar branch will be created if they don't already exist.
     Any unknown or modified files will be commited to the branch.
     """
     try:
         BzrDir.open(self.repo_location)
     except bzrlib.errors.NotBranchError, e:
         logger.info("Location [%s] is not a Bazaar branch. Will turn it into one." % self.repo_location)
         BzrDir.create_branch_convenience(self.repo_location)
Ejemplo n.º 16
0
 def test_init(self):
     self.run_bzr("init-repo a")
     self.run_bzr("init --format=default a/b")
     dir = BzrDir.open('a')
     self.assertIs(dir.open_repository().is_shared(), True)
     self.assertRaises(errors.NotBranchError, dir.open_branch)
     self.assertRaises(errors.NoWorkingTree, dir.open_workingtree)
     bdir = BzrDir.open('a/b')
     bdir.open_branch()
     self.assertRaises(errors.NoRepositoryPresent, bdir.open_repository)
     wt = bdir.open_workingtree()
Ejemplo n.º 17
0
    def newtree_cb(self, menu, vfs_file):
        # We can only cope with local files
        if vfs_file.get_uri_scheme() != 'file':
            return

        file = vfs_file.get_uri()

        # We only want to continue here if we get a NotBranchError
        try:
            tree, path = WorkingTree.open_containing(file)
        except NotBranchError:
            BzrDir.create_standalone_workingtree(file)
Ejemplo n.º 18
0
    def push(self,
             db_branch_id,
             bzr_branch,
             required_format,
             stacked_on_url=None):
        """Push up `bzr_branch` as the Bazaar branch for `code_import`.

        :return: A boolean that is true if the push was non-trivial
            (i.e. actually transferred revisions).
        """
        self.transport.create_prefix()
        target_url = self._getMirrorURL(db_branch_id, push=True)
        try:
            remote_branch = Branch.open(target_url)
        except NotBranchError:
            remote_branch = BzrDir.create_branch_and_repo(
                target_url, format=required_format)
            old_branch = None
        else:
            if remote_branch.bzrdir.needs_format_conversion(required_format):
                # For upgrades, push to a new branch in
                # the new format. When done pushing,
                # retire the old .bzr directory and rename
                # the new one in place.
                old_branch = remote_branch
                upgrade_url = urljoin(target_url, "backup.bzr")
                try:
                    remote_branch.bzrdir.root_transport.delete_tree(
                        'backup.bzr')
                except NoSuchFile:
                    pass
                remote_branch = BzrDir.create_branch_and_repo(
                    upgrade_url, format=required_format)
            else:
                old_branch = None
        # This can be done safely, since only modern formats are used to
        # import to.
        if stacked_on_url is not None:
            remote_branch.set_stacked_on_url(stacked_on_url)
        pull_result = remote_branch.pull(bzr_branch, overwrite=True)
        # Because of the way we do incremental imports, there may be revisions
        # in the branch's repo that are not in the ancestry of the branch tip.
        # We need to transfer them too.
        remote_branch.repository.fetch(bzr_branch.repository)
        if old_branch is not None:
            # The format has changed; move the new format
            # branch in place.
            base_transport = old_branch.bzrdir.root_transport
            base_transport.delete_tree('.bzr')
            base_transport.rename("backup.bzr/.bzr", ".bzr")
            base_transport.rmdir("backup.bzr")
        return pull_result.old_revid != pull_result.new_revid
Ejemplo n.º 19
0
    def test_switch_branches(self):
        # switch_branches moves a branch to the new location and places a
        # branch (with no revisions) stacked on the new branch in the old
        # location.

        chroot_server = ChrootServer(self.get_transport())
        chroot_server.start_server()
        self.addCleanup(chroot_server.stop_server)
        scheme = chroot_server.get_url().rstrip('/:')

        old_branch = FakeBranch(1)
        self.get_transport(old_branch.unique_name).create_prefix()
        tree = self.make_branch_and_tree(old_branch.unique_name)
        # XXX: AaronBentley 2010-08-06 bug=614404: a bzr username is
        # required to generate the revision-id.
        with override_environ(BZR_EMAIL='*****@*****.**'):
            tree.commit(message='.')

        new_branch = FakeBranch(2)

        switch_branches('.', scheme, old_branch, new_branch)

        # Post conditions:
        # 1. unstacked branch in new_branch's location
        # 2. stacked branch with no revisions in repo at old_branch
        # 3. last_revision() the same for two branches

        old_location_bzrdir = BzrDir.open(
            str(URI(scheme=scheme, host='',
                    path='/' + old_branch.unique_name)))
        new_location_bzrdir = BzrDir.open(
            str(URI(scheme=scheme, host='',
                    path='/' + new_branch.unique_name)))

        old_location_branch = old_location_bzrdir.open_branch()
        new_location_branch = new_location_bzrdir.open_branch()

        # 1. unstacked branch in new_branch's location
        self.assertRaises(NotStacked, new_location_branch.get_stacked_on_url)

        # 2. stacked branch with no revisions in repo at old_branch
        self.assertEqual('/' + new_branch.unique_name,
                         old_location_branch.get_stacked_on_url())
        self.assertEqual(
            [],
            old_location_bzrdir.open_repository().all_revision_ids())

        # 3. last_revision() the same for two branches
        self.assertEqual(old_location_branch.last_revision(),
                         new_location_branch.last_revision())
Ejemplo n.º 20
0
    def ensure_repo_consistency(self):
        """ Makes sure the self.repo_location directory is a Bazaar branch.
        The repo and Bazaar branch will be created if they don't already exist.
        Any unknown or modified files will be commited to the branch.
        Also, 'bzr whoami' will be set to the current user so that all commands
        can be traced back to an actual person (assuming everyone has their
        own logins).
        """

        try:
            BzrDir.open(self.repo_location)
        except bzrlib.errors.NotBranchError, e:
            logger.info('Location [{}] is not a Bazaar branch. Will turn it into one.'.format(self.repo_location))
            BzrDir.create_branch_convenience(self.repo_location)
Ejemplo n.º 21
0
    def push(self, db_branch_id, bzr_branch, required_format,
             stacked_on_url=None):
        """Push up `bzr_branch` as the Bazaar branch for `code_import`.

        :return: A boolean that is true if the push was non-trivial
            (i.e. actually transferred revisions).
        """
        self.transport.create_prefix()
        target_url = self._getMirrorURL(db_branch_id)
        try:
            remote_branch = Branch.open(target_url)
        except NotBranchError:
            remote_branch = BzrDir.create_branch_and_repo(
                target_url, format=required_format)
            old_branch = None
        else:
            if remote_branch.bzrdir.needs_format_conversion(
                    required_format):
                # For upgrades, push to a new branch in
                # the new format. When done pushing,
                # retire the old .bzr directory and rename
                # the new one in place.
                old_branch = remote_branch
                upgrade_url = urljoin(target_url, "backup.bzr")
                try:
                    remote_branch.bzrdir.root_transport.delete_tree(
                        'backup.bzr')
                except NoSuchFile:
                    pass
                remote_branch = BzrDir.create_branch_and_repo(
                    upgrade_url, format=required_format)
            else:
                old_branch = None
        # This can be done safely, since only modern formats are used to
        # import to.
        if stacked_on_url is not None:
            remote_branch.set_stacked_on_url(stacked_on_url)
        pull_result = remote_branch.pull(bzr_branch, overwrite=True)
        # Because of the way we do incremental imports, there may be revisions
        # in the branch's repo that are not in the ancestry of the branch tip.
        # We need to transfer them too.
        remote_branch.repository.fetch(bzr_branch.repository)
        if old_branch is not None:
            # The format has changed; move the new format
            # branch in place.
            base_transport = old_branch.bzrdir.root_transport
            base_transport.delete_tree('.bzr')
            base_transport.rename("backup.bzr/.bzr", ".bzr")
            base_transport.rmdir("backup.bzr")
        return pull_result.old_revid != pull_result.new_revid
Ejemplo n.º 22
0
    def apply_pack(self, refs, read):
        """ apply pack from client to current repository """

        fd, path = tempfile.mkstemp(suffix=".pack")
        f = os.fdopen(fd, 'w')
        f.write(read())
        f.close()

        p = PackData(path)
        entries = p.sorted_entries()
        write_pack_index_v2(path[:-5] + ".idx", entries,
                            p.calculate_checksum())

        def get_objects():
            pack = Pack(path[:-5])
            for obj in pack.iterobjects():
                yield obj

        target = Repository.open(self.directory)

        target.lock_write()
        try:
            target.start_write_group()
            try:
                import_git_objects(target, self.mapping, iter(get_objects()))
            finally:
                target.commit_write_group()
        finally:
            target.unlock()

        for oldsha, sha, ref in refs:
            if ref[:11] == 'refs/heads/':
                branch_nick = ref[11:]

                try:
                    target_dir = BzrDir.open(self.directory + "/" +
                                             branch_nick)
                except:
                    target_dir = BzrDir.create(self.directory + "/" +
                                               branch_nick)

                try:
                    target_branch = target_dir.open_branch()
                except:
                    target_branch = target_dir.create_branch()

                rev_id = self.mapping.revision_id_foreign_to_bzr(sha)
                target_branch.generate_revision_history(rev_id)
Ejemplo n.º 23
0
 def run(self, repository=None):
     from bzrlib.bzrdir import BzrDir
     dir, _ = BzrDir.open_containing(repository)
     r = dir.find_repository()
     from bzrlib.plugins.rewrite.pseudonyms import find_pseudonyms
     for pseudonyms in find_pseudonyms(r, r.all_revision_ids()):
         self.outf.write(", ".join(pseudonyms) + "\n")
Ejemplo n.º 24
0
 def test_post_push_bound_branch(self):
     # pushing to a bound branch should pass in the master branch to the
     # hook, allowing the correct number of emails to be sent, while still
     # allowing hooks that want to modify the target to do so to both
     # instances.
     target = self.make_branch('target')
     local = self.make_branch('local')
     try:
         local.bind(target)
     except errors.UpgradeRequired:
         # We can't bind this format to itself- typically it is the local
         # branch that doesn't support binding.  As of May 2007
         # remotebranches can't be bound.  Let's instead make a new local
         # branch of the default type, which does allow binding.
         # See https://bugs.launchpad.net/bzr/+bug/112020
         local = BzrDir.create_branch_convenience('local2')
         local.bind(target)
     source = self.make_branch('source')
     Branch.hooks.install_named_hook('post_push',
                                     self.capture_post_push_hook, None)
     source.push(local)
     # with nothing there we should still get a notification, and
     # have both branches locked at the notification time.
     self.assertEqual([('post_push', source, local.base, target.base, 0,
                        NULL_REVISION, 0, NULL_REVISION, True, True, True)],
                      self.hook_calls)
Ejemplo n.º 25
0
 def test_post_push_bound_branch(self):
     # pushing to a bound branch should pass in the master branch to the
     # hook, allowing the correct number of emails to be sent, while still
     # allowing hooks that want to modify the target to do so to both 
     # instances.
     target = self.make_branch('target')
     local = self.make_branch('local')
     try:
         local.bind(target)
     except errors.UpgradeRequired:
         # We can't bind this format to itself- typically it is the local
         # branch that doesn't support binding.  As of May 2007
         # remotebranches can't be bound.  Let's instead make a new local
         # branch of the default type, which does allow binding.
         # See https://bugs.launchpad.net/bzr/+bug/112020
         local = BzrDir.create_branch_convenience('local2')
         local.bind(target)
     source = self.make_branch('source')
     Branch.hooks.install_named_hook('post_push',
                                     self.capture_post_push_hook, None)
     source.push(local)
     # with nothing there we should still get a notification, and
     # have both branches locked at the notification time.
     self.assertEqual([
         ('post_push', source, local.base, target.base, 0, NULL_REVISION,
          0, NULL_REVISION, True, True, True)
         ],
         self.hook_calls)
Ejemplo n.º 26
0
 def _find(self, path):
     """try to find a repository from path upwards
     
     This operates precisely like 'bzrdir.find_repository'.
     
     :return: (relpath, rich_root, tree_ref, external_lookup) flags. All are
         strings, relpath is a / prefixed path, and the other three are
         either 'yes' or 'no'.
     :raises errors.NoRepositoryPresent: When there is no repository
         present.
     """
     bzrdir = BzrDir.open_from_transport(
         self.transport_from_client_path(path))
     repository = bzrdir.find_repository()
     # the relpath of the bzrdir in the found repository gives us the 
     # path segments to pop-out.
     relpath = repository.bzrdir.root_transport.relpath(
         bzrdir.root_transport.base)
     if len(relpath):
         segments = ['..'] * len(relpath.split('/'))
     else:
         segments = []
     rich_root = self._boolean_to_yes_no(repository.supports_rich_root())
     tree_ref = self._boolean_to_yes_no(
         repository._format.supports_tree_reference)
     external_lookup = self._boolean_to_yes_no(
         repository._format.supports_external_lookups)
     return '/'.join(segments), rich_root, tree_ref, external_lookup
Ejemplo n.º 27
0
    def setup_tree(self):
        wt = BzrDir.create_standalone_workingtree('.')
        wt.commit("base A", allow_pointless=True, rev_id='A')
        wt.commit("base B", allow_pointless=True, rev_id='B')
        wt.commit("base C", allow_pointless=True, rev_id='C')

        return wt
Ejemplo n.º 28
0
    def run(self, base_dir='.', overwrite=False, verbose=False):
        if not os.path.exists(base_dir):
            print 'Base directory does not exist.'
            return 3

        retcode = 0

        for root, dirs, files in os.walk(base_dir):
            to_remove = []
            for i, d in enumerate(dirs):
                if d in ('{arch}', 'CVS', '.svn', '_svn', '.bzr'):
                    to_remove.append(i)
                elif d.endswith('.tmp') or d.startswith(',,'):
                    to_remove.append(i)
            to_remove.reverse()
            for i in to_remove:
                dirs.pop(i)

            try:
                try:
                    br_dir = BzrDir.open(root)
                except NotBranchError:
                    continue
                except UnsupportedFormatError, e:
                    print '=' * 50
                    print 'Branch at %s' % root
                    print 'in an unsupported format'
                    print e
                    print

                r = pull_branch(br_dir, verbose=verbose, overwrite=overwrite)
                retcode = max(retcode, r)
            except KeyboardInterrupt:
                raise
Ejemplo n.º 29
0
    def __init__(self, repository):
        from os.path import split
        from bzrlib import version_info, IGNORE_FILENAME

        if version_info > (0,9):
            from bzrlib.ignores import add_runtime_ignores, parse_ignore_file
        else:
            from bzrlib import DEFAULT_IGNORE

        WorkingDir.__init__(self, repository)
        # TODO: check if there is a "repository" in the configuration,
        # and use it as a bzr repository
        self.ignored = []
        self._working_tree = None

        # The bzr repository may have some plugins that needs to be activated
        load_plugins()

        try:
            bzrdir = BzrDir.open(self.repository.basedir)
            wt = self._working_tree = bzrdir.open_workingtree()

            # read .bzrignore for _addSubtree()
            if wt.has_filename(IGNORE_FILENAME):
                f = wt.get_file_byname(IGNORE_FILENAME)
                if version_info > (0,9):
                    self.ignored.extend(parse_ignore_file(f))
                else:
                    self.ignored.extend([ line.rstrip("\n\r") for line in f.readlines() ])
                f.close()
        except errors.NotBranchError, errors.NoWorkingTree:
            pass
Ejemplo n.º 30
0
def list_branches(repo):
    trans = repo.bzrdir.root_transport
    dirs_to_check = ['.']
    branches = []
    while len(dirs_to_check) > 0:
        filename = dirs_to_check.pop(0)
        if stat.S_ISDIR(trans.stat(filename).st_mode):
            # is this a branch inside the given repository?
            try:
                br_dir = BzrDir.open(trans.abspath(filename))
                branch = br_dir.open_branch()
            except errors.NotBranchError:
                branch = None

            # if we have a branch, add it to the result set, provided
            # that it uses the same repository.
            if branch is not None:
                # if the branch uses a different repository, then
                # don't include it.
                if (branch.repository.bzrdir.root_transport.base !=
                        trans.base):
                    continue
                # XXX: hack to make sure the branch is using the same
                # repository instance, for locking purposes
                branch.repository = repo
                branches.append(branch)

            # extend the list of dirs to check.
            dirs_to_check.extend([
                urlutils.join(filename, name)
                for name in trans.list_dir(filename) if name != '.bzr'
            ])
    return branches
Ejemplo n.º 31
0
def list_branches(repo):
    trans = repo.bzrdir.root_transport
    dirs_to_check = ['.']
    branches = []
    while len(dirs_to_check) > 0:
        filename = dirs_to_check.pop(0)
        if stat.S_ISDIR(trans.stat(filename).st_mode):
            # is this a branch inside the given repository?
            try:
                br_dir = BzrDir.open(trans.abspath(filename))
                branch = br_dir.open_branch()
            except errors.NotBranchError:
                branch = None

            # if we have a branch, add it to the result set, provided
            # that it uses the same repository.
            if branch is not None:
                # if the branch uses a different repository, then
                # don't include it.
                if (branch.repository.bzrdir.root_transport.base !=
                    trans.base):
                    continue
                # XXX: hack to make sure the branch is using the same
                # repository instance, for locking purposes
                branch.repository = repo
                branches.append(branch)

            # extend the list of dirs to check.
            dirs_to_check.extend([urlutils.join(filename, name)
                                  for name in trans.list_dir(filename)
                                  if name != '.bzr'])
    return branches
Ejemplo n.º 32
0
Archivo: bzr.py Proyecto: ilius/starcal
def prepareObj(obj):
    (
        tree,
        branch,
        repo,
        relpath,
    ) = BzrDir.open_containing_tree_branch_or_repository(obj.vcsDir)
    obj.branch = branch
    obj.repo = repo
    ###
    obj.est = EventSearchTree()
    obj.firstRev = None
    obj.lastRev = None
    for (
            rev_id,
            depth,
            revno,
            end_of_merge,
    ) in branch.iter_merge_sorted_revisions(direction="forward"):
        rev = obj.repo.get_revision(rev_id)
        epoch = rev.timestamp
        obj.est.add(epoch, epoch, rev_id)
        if not obj.firstRev:
            obj.firstRev = rev
        obj.lastRev = rev
Ejemplo n.º 33
0
 def _find(self, path):
     """try to find a repository from path upwards
     
     This operates precisely like 'bzrdir.find_repository'.
     
     :return: (relpath, rich_root, tree_ref, external_lookup) flags. All are
         strings, relpath is a / prefixed path, and the other three are
         either 'yes' or 'no'.
     :raises errors.NoRepositoryPresent: When there is no repository
         present.
     """
     bzrdir = BzrDir.open_from_transport(
         self.transport_from_client_path(path))
     repository = bzrdir.find_repository()
     # the relpath of the bzrdir in the found repository gives us the
     # path segments to pop-out.
     relpath = repository.bzrdir.root_transport.relpath(
         bzrdir.root_transport.base)
     if len(relpath):
         segments = ['..'] * len(relpath.split('/'))
     else:
         segments = []
     rich_root = self._boolean_to_yes_no(repository.supports_rich_root())
     tree_ref = self._boolean_to_yes_no(
         repository._format.supports_tree_reference)
     external_lookup = self._boolean_to_yes_no(
         repository._format.supports_external_lookups)
     return '/'.join(segments), rich_root, tree_ref, external_lookup
Ejemplo n.º 34
0
Archivo: bzr.py Proyecto: ilius/starcal
def prepareObj(obj):
	(
		tree,
		branch,
		repo,
		relpath,
	) = BzrDir.open_containing_tree_branch_or_repository(obj.vcsDir)
	obj.branch = branch
	obj.repo = repo
	###
	obj.est = EventSearchTree()
	obj.firstRev = None
	obj.lastRev = None
	for (
		rev_id,
		depth,
		revno,
		end_of_merge,
	) in branch.iter_merge_sorted_revisions(direction="forward"):
		rev = obj.repo.get_revision(rev_id)
		epoch = rev.timestamp
		obj.est.add(epoch, epoch, rev_id)
		if not obj.firstRev:
			obj.firstRev = rev
		obj.lastRev = rev
Ejemplo n.º 35
0
    def setup_tree(self):
        wt = BzrDir.create_standalone_workingtree('.')
        wt.commit("base A", allow_pointless=True, rev_id='A')
        wt.commit("base B", allow_pointless=True, rev_id='B')
        wt.commit("base C", allow_pointless=True, rev_id='C')

        return wt
Ejemplo n.º 36
0
    def do(self, path, network_name, shared):
        """Create a repository in the bzr dir at path.

        This operates precisely like 'bzrdir.create_repository'.

        If a bzrdir is not present, an exception is propagated
        rather than 'no branch' because these are different conditions (and
        this method should only be called after establishing that a bzr dir
        exists anyway).

        This is the initial version of this method introduced to the smart
        server for 1.13.

        :param path: The path to the bzrdir.
        :param network_name: The network name of the repository type to create.
        :param shared: The value to pass create_repository for the shared
            parameter.
        :return: (ok, rich_root, tree_ref, external_lookup, network_name)
        """
        bzrdir = BzrDir.open_from_transport(
            self.transport_from_client_path(path))
        shared = shared == 'True'
        format = repository.network_format_registry.get(network_name)
        bzrdir.repository_format = format
        result = format.initialize(bzrdir, shared=shared)
        rich_root, tree_ref, external_lookup = self._format_to_capabilities(
            result._format)
        return SuccessfulSmartServerResponse(
            ('ok', rich_root, tree_ref, external_lookup,
             result._format.network_name()))
Ejemplo n.º 37
0
    def do(self, path, network_name):
        """Create a branch in the bzr dir at path.

        This operates precisely like 'bzrdir.create_branch'.

        If a bzrdir is not present, an exception is propogated
        rather than 'no branch' because these are different conditions (and
        this method should only be called after establishing that a bzr dir
        exists anyway).

        This is the initial version of this method introduced to the smart
        server for 1.13.

        :param path: The path to the bzrdir.
        :param network_name: The network name of the branch type to create.
        :return: ('ok', branch_format, repo_path, rich_root, tree_ref,
            external_lookup, repo_format)
        """
        bzrdir = BzrDir.open_from_transport(
            self.transport_from_client_path(path))
        format = branch.network_format_registry.get(network_name)
        bzrdir.branch_format = format
        result = format.initialize(bzrdir, name="")
        rich_root, tree_ref, external_lookup = self._format_to_capabilities(
            result.repository._format)
        branch_format = result._format.network_name()
        repo_format = result.repository._format.network_name()
        repo_path = self._repo_relpath(bzrdir.root_transport,
                                       result.repository)
        # branch format, repo relpath, rich_root, tree_ref, external_lookup,
        # repo_network_name
        return SuccessfulSmartServerResponse(
            ('ok', branch_format, repo_path, rich_root, tree_ref,
             external_lookup, repo_format))
Ejemplo n.º 38
0
    def do(self, path, network_name, shared):
        """Create a repository in the bzr dir at path.

        This operates precisely like 'bzrdir.create_repository'.

        If a bzrdir is not present, an exception is propagated
        rather than 'no branch' because these are different conditions (and
        this method should only be called after establishing that a bzr dir
        exists anyway).

        This is the initial version of this method introduced to the smart
        server for 1.13.

        :param path: The path to the bzrdir.
        :param network_name: The network name of the repository type to create.
        :param shared: The value to pass create_repository for the shared
            parameter.
        :return: (ok, rich_root, tree_ref, external_lookup, network_name)
        """
        bzrdir = BzrDir.open_from_transport(
            self.transport_from_client_path(path))
        shared = shared == 'True'
        format = repository.network_format_registry.get(network_name)
        bzrdir.repository_format = format
        result = format.initialize(bzrdir, shared=shared)
        rich_root, tree_ref, external_lookup = self._format_to_capabilities(
            result._format)
        return SuccessfulSmartServerResponse(('ok', rich_root, tree_ref,
            external_lookup, result._format.network_name()))
Ejemplo n.º 39
0
 def do(self, path, *args):
     """Open a BzrDir at path, and return `self.do_bzrdir_request(*args)`."""
     try:
         self._bzrdir = BzrDir.open_from_transport(
             self.transport_from_client_path(path))
     except errors.NotBranchError, e:
         return FailedSmartServerResponse(('nobranch',))
Ejemplo n.º 40
0
    def do(self, path, network_name):
        """Create a branch in the bzr dir at path.

        This operates precisely like 'bzrdir.create_branch'.

        If a bzrdir is not present, an exception is propogated
        rather than 'no branch' because these are different conditions (and
        this method should only be called after establishing that a bzr dir
        exists anyway).

        This is the initial version of this method introduced to the smart
        server for 1.13.

        :param path: The path to the bzrdir.
        :param network_name: The network name of the branch type to create.
        :return: ('ok', branch_format, repo_path, rich_root, tree_ref,
            external_lookup, repo_format)
        """
        bzrdir = BzrDir.open_from_transport(
            self.transport_from_client_path(path))
        format = branch.network_format_registry.get(network_name)
        bzrdir.branch_format = format
        result = format.initialize(bzrdir, name="")
        rich_root, tree_ref, external_lookup = self._format_to_capabilities(
            result.repository._format)
        branch_format = result._format.network_name()
        repo_format = result.repository._format.network_name()
        repo_path = self._repo_relpath(bzrdir.root_transport,
            result.repository)
        # branch format, repo relpath, rich_root, tree_ref, external_lookup,
        # repo_network_name
        return SuccessfulSmartServerResponse(('ok', branch_format, repo_path,
            rich_root, tree_ref, external_lookup, repo_format))
Ejemplo n.º 41
0
 def do(self, path, *args):
     """Open a BzrDir at path, and return `self.do_bzrdir_request(*args)`."""
     try:
         self._bzrdir = BzrDir.open_from_transport(
             self.transport_from_client_path(path))
     except errors.NotBranchError, e:
         return FailedSmartServerResponse(('nobranch', ))
Ejemplo n.º 42
0
Archivo: repo.py Proyecto: saulm/zato
    def ensure_repo_consistency(self):
        """ Makes sure the self.repo_location directory is a Bazaar branch.
        The repo and Bazaar branch will be created if they don't already exist.
        Any unknown or modified files will be commited to the branch.
        Also, 'bzr whoami' will be set to the current user so that all commands
        can be traced back to an actual person (assuming everyone has their
        own logins).
        """

        try:
            BzrDir.open(self.repo_location)
        except bzrlib.errors.NotBranchError, e:
            logger.info(
                'Location [{}] is not a Bazaar branch. Will turn it into one.'.
                format(self.repo_location))
            BzrDir.create_branch_convenience(self.repo_location)
Ejemplo n.º 43
0
 def test_make_repository(self):
     out, err = self.run_bzr("init-repository a")
     self.assertEqual(out, "")
     self.assertEqual(err, "")
     dir = BzrDir.open('a')
     self.assertIs(dir.open_repository().is_shared(), True)
     self.assertRaises(errors.NotBranchError, dir.open_branch)
     self.assertRaises(errors.NoWorkingTree, dir.open_workingtree)
Ejemplo n.º 44
0
 def test_init_repo_existing_dir(self):
     """Make repo in existing directory.
     
     (Malone #38331)
     """
     out, err = self.run_bzr("init-repository .")
     dir = BzrDir.open('.')
     self.assertTrue(dir.open_repository())
Ejemplo n.º 45
0
 def test_branch(self):
     self.run_bzr("init-repo a")
     self.run_bzr("init --format=default a/b")
     self.run_bzr('branch a/b a/c')
     cdir = BzrDir.open('a/c')
     cdir.open_branch()
     self.assertRaises(errors.NoRepositoryPresent, cdir.open_repository)
     cdir.open_workingtree()
Ejemplo n.º 46
0
 def prepare_simple_history(self):
     """Prepare and return a working tree with one commit of one file"""
     # Commit with modified file should say so
     wt = BzrDir.create_standalone_workingtree('.')
     self.build_tree(['hello.txt', 'extra.txt'])
     wt.add(['hello.txt'])
     wt.commit(message='added')
     return wt
Ejemplo n.º 47
0
 def prepare_simple_history(self):
     """Prepare and return a working tree with one commit of one file"""
     # Commit with modified file should say so
     wt = BzrDir.create_standalone_workingtree('.')
     self.build_tree(['hello.txt', 'extra.txt'])
     wt.add(['hello.txt'])
     wt.commit(message='added')
     return wt
Ejemplo n.º 48
0
    def run(self, location=None, remember=False, directory=None, 
            no_rebase=False):
        from bzrlib import urlutils
        from bzrlib.bzrdir import BzrDir
        from bzrlib.errors import BzrCommandError, NoWorkingTree
        from bzrlib.trace import info
        from bzrlib.workingtree import WorkingTree
        from upgrade import update_workingtree_fileids

        if directory is None:
            directory = "."
        try:
            source_wt = WorkingTree.open_containing(directory)[0]
            source_branch = source_wt.branch
        except NoWorkingTree:
            source_branch = Branch.open_containing(directory)[0]
            source_wt = None
        stored_loc = source_branch.get_push_location()
        if location is None:
            if stored_loc is None:
                raise BzrCommandError("No push location known or specified.")
            else:
                display_url = urlutils.unescape_for_display(stored_loc,
                        self.outf.encoding)
                self.outf.write("Using saved location: %s\n" % display_url)
                location = stored_loc

        bzrdir = BzrDir.open(location)
        target_branch = bzrdir.open_branch()
        target_branch.lock_write()
        try:
            if not isinstance(target_branch, ForeignBranch):
                info("target branch is not a foreign branch, using regular push.")
                target_branch.pull(source_branch)
                no_rebase = True
            else:
                revid_map = target_branch.dpull(source_branch)
            # We successfully created the target, remember it
            if source_branch.get_push_location() is None or remember:
                source_branch.set_push_location(target_branch.base)
            if not no_rebase:
                _, old_last_revid = source_branch.last_revision_info()
                new_last_revid = revid_map[old_last_revid]
                if source_wt is not None:
                    source_wt.pull(target_branch, overwrite=True, 
                                   stop_revision=new_last_revid)
                    source_wt.lock_write()
                    try:
                        update_workingtree_fileids(source_wt, 
                            source_wt.branch.repository.revision_tree(old_last_revid),
                            source_wt.branch.repository.revision_tree(new_last_revid))
                    finally:
                        source_wt.unlock()
                else:
                    source_branch.pull(target_branch, overwrite=True, 
                                       stop_revision=new_last_revid)
        finally:
            target_branch.unlock()
Ejemplo n.º 49
0
    def test_lock_with_magic_id(self):
        # When the subprocess locks a branch, it is locked with the right ID.
        class PullerMonitorProtocolWithLockID(
            scheduler.PullerMonitorProtocol):
            """Subclass of PullerMonitorProtocol with a lock_id method.

            This protocol defines a method that records on the listener the
            lock id reported by the subprocess.
            """

            def do_lock_id(self, id):
                """Record the lock id on the listener."""
                self.listener.lock_ids.append(id)

        class PullerMasterWithLockID(scheduler.PullerMaster):
            """A subclass of PullerMaster that allows recording of lock ids.
            """

            protocol_class = PullerMonitorProtocolWithLockID

        check_lock_id_script = """
        branch.lock_write()
        protocol.mirrorFailed('a', 'b')
        protocol.sendEvent(
            'lock_id', branch.control_files._lock.peek().get('user'))
        sys.stdout.flush()
        branch.unlock()
        """

        puller_master = self.makePullerMaster(
            PullerMasterWithLockID, check_lock_id_script)
        puller_master.lock_ids = []

        # We need to create a branch at the destination_url, so that the
        # subprocess can actually create a lock.
        BzrDir.create_branch_convenience(puller_master.destination_url)

        deferred = puller_master.mirror().addErrback(self._dumpError)

        def checkID(ignored):
            self.assertEqual(
                puller_master.lock_ids,
                [get_lock_id_for_branch_id(puller_master.branch_id)])

        return deferred.addCallback(checkID)
Ejemplo n.º 50
0
    def test_lock_with_magic_id(self):
        # When the subprocess locks a branch, it is locked with the right ID.
        class PullerMonitorProtocolWithLockID(
            scheduler.PullerMonitorProtocol):
            """Subclass of PullerMonitorProtocol with a lock_id method.

            This protocol defines a method that records on the listener the
            lock id reported by the subprocess.
            """

            def do_lock_id(self, id):
                """Record the lock id on the listener."""
                self.listener.lock_ids.append(id)

        class PullerMasterWithLockID(scheduler.PullerMaster):
            """A subclass of PullerMaster that allows recording of lock ids.
            """

            protocol_class = PullerMonitorProtocolWithLockID

        check_lock_id_script = """
        branch.lock_write()
        protocol.mirrorFailed('a', 'b')
        protocol.sendEvent(
            'lock_id', branch.control_files._lock.peek().get('user'))
        sys.stdout.flush()
        branch.unlock()
        """

        puller_master = self.makePullerMaster(
            PullerMasterWithLockID, check_lock_id_script)
        puller_master.lock_ids = []

        # We need to create a branch at the destination_url, so that the
        # subprocess can actually create a lock.
        BzrDir.create_branch_convenience(puller_master.destination_url)

        deferred = puller_master.mirror().addErrback(self._dumpError)

        def checkID(ignored):
            self.assertEqual(
                puller_master.lock_ids,
                [get_lock_id_for_branch_id(puller_master.branch_id)])

        return deferred.addCallback(checkID)
Ejemplo n.º 51
0
    def apply_pack(self, refs, read):
        """ apply pack from client to current repository """

        fd, path = tempfile.mkstemp(suffix=".pack")
        f = os.fdopen(fd, 'w')
        f.write(read())
        f.close()

        p = PackData(path)
        entries = p.sorted_entries()
        write_pack_index_v2(path[:-5]+".idx", entries, p.calculate_checksum())

        def get_objects():
            pack = Pack(path[:-5])
            for obj in pack.iterobjects():
                yield obj

        target = Repository.open(self.directory)

        target.lock_write()
        try:
            target.start_write_group()
            try:
                import_git_objects(target, self.mapping, iter(get_objects()))
            finally:
                target.commit_write_group()
        finally:
            target.unlock()

        for oldsha, sha, ref in refs:
            if ref[:11] == 'refs/heads/':
                branch_nick = ref[11:]

                try:
                    target_dir = BzrDir.open(self.directory + "/" + branch_nick)
                except:
                    target_dir = BzrDir.create(self.directory + "/" + branch_nick)

                try:
                    target_branch = target_dir.open_branch()
                except:
                    target_branch = target_dir.create_branch()

                rev_id = self.mapping.revision_id_foreign_to_bzr(sha)
                target_branch.generate_revision_history(rev_id)
Ejemplo n.º 52
0
    def addTreeReference(self, tree):
        """Add a tree reference to a tree and commit.

        :param tree: A Bazaar WorkingTree to add a tree to.
        """
        sub_branch = BzrDir.create_branch_convenience(
            tree.bzrdir.root_transport.clone('sub').base)
        tree.add_reference(sub_branch.bzrdir.open_workingtree())
        tree.commit('added tree reference', committer='*****@*****.**')
Ejemplo n.º 53
0
 def get_refs(self):
     """ return a dict of all tags and branches in repository (and shas) """
     ret = {}
     repo_dir = BzrDir.open(self.directory)
     repo = repo_dir.open_repository()
     for branch in repo.find_branches(using=True):
         #FIXME: Need to get branch path relative to its repository and use this instead of nick
         ret["refs/heads/"+branch.nick] = self.mapping.revision_id_bzr_to_foreign(branch.last_revision())
     return ret
Ejemplo n.º 54
0
    def __init__(self, source, revision=None):
        self.revision = revision and int(revision)
        self.project = None
        self.new = False
        self.zipfile = None
        self.config = None

        if isinstance(source, basestring):
            self.config = self._newconf(source)
        elif isinstance(source, ZipFile):
            self.zipfile = source
            try:
                conf = StringIO.StringIO(self.zipfile.read('sharetx.conf'))
                self.config = SafeConfigParser()
                self.config.readfp(conf)
                conf.close()
            except KeyError:
                self.config = self._newconf(str(uuid.uuid1()))
                self.new = True

        if not self.config:
            raise 'Configuration not found', source

        self.checkout_path = mkdtemp()
        self.branch_path = os.path.join(userdir(session['username']),
                                        self.config.get('sharetx', 'uri'))

        if self.new:
            if os.path.exists(self.branch_path):
                raise 'Project already exists', self.branch_path
    
            os.makedirs(self.branch_path)
            self.branch = BzrDir.create_branch_convenience(self.branch_path)
        else:
            self.branch = Branch.open(self.branch_path)

        if self.new:
            self.checkout()
            self.extract()
            conf = open(os.path.join(self.checkout_path, 'sharetx.conf'), 'wb')
            self.config.write(conf)
            conf.close()
            self.wt.add('sharetx.conf')
        elif self.zipfile:
            self.extract()
        else:
            self.checkout()

        self.project = CeltxRDFProject(self.checkout_path)

        # Re-read configuration and check version
        conf = os.path.join(self.checkout_path, 'sharetx.conf')
        self.config = SafeConfigParser()
        self.config.read(conf)
        version = self.config.get('sharetx', 'version')
        if version != '1':
            raise 'Not a valid version: %s' % version
Ejemplo n.º 55
0
    def setUp(self):
        super(TestsNeedingReweave, self).setUp()

        t = self.get_transport()
        # an empty inventory with no revision for testing with.
        repo = self.make_repository('inventory_without_revision')
        repo.lock_write()
        repo.start_write_group()
        inv = Inventory(revision_id='missing')
        inv.root.revision = 'missing'
        repo.add_inventory('missing', inv, [])
        repo.commit_write_group()
        repo.unlock()

        def add_commit(repo, revision_id, parent_ids):
            repo.lock_write()
            repo.start_write_group()
            inv = Inventory(revision_id=revision_id)
            inv.root.revision = revision_id
            root_id = inv.root.file_id
            sha1 = repo.add_inventory(revision_id, inv, parent_ids)
            repo.texts.add_lines((root_id, revision_id), [], [])
            rev = bzrlib.revision.Revision(
                timestamp=0,
                timezone=None,
                committer="Foo Bar <*****@*****.**>",
                message="Message",
                inventory_sha1=sha1,
                revision_id=revision_id)
            rev.parent_ids = parent_ids
            repo.add_revision(revision_id, rev)
            repo.commit_write_group()
            repo.unlock()

        # an empty inventory with no revision for testing with.
        # this is referenced by 'references_missing' to let us test
        # that all the cached data is correctly converted into ghost links
        # and the referenced inventory still cleaned.
        repo = self.make_repository('inventory_without_revision_and_ghost')
        repo.lock_write()
        repo.start_write_group()
        repo.add_inventory('missing', inv, [])
        repo.commit_write_group()
        repo.unlock()
        add_commit(repo, 'references_missing', ['missing'])

        # a inventory with no parents and the revision has parents..
        # i.e. a ghost.
        repo = self.make_repository('inventory_one_ghost')
        add_commit(repo, 'ghost', ['the_ghost'])

        # a inventory with a ghost that can be corrected now.
        t.copy_tree('inventory_one_ghost', 'inventory_ghost_present')
        bzrdir_url = self.get_url('inventory_ghost_present')
        bzrdir = BzrDir.open(bzrdir_url)
        repo = bzrdir.open_repository()
        add_commit(repo, 'the_ghost', [])
Ejemplo n.º 56
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.º 57
0
    def test_bzr_serve_inet_readwrite(self):
        # Make a branch
        self.make_branch('.')

        process, transport = self.start_server_inet(['--allow-writes'])

        # We get a working branch
        branch = BzrDir.open_from_transport(transport).open_branch()
        self.make_read_requests(branch)
        self.assertInetServerShutsdownCleanly(process)
Ejemplo n.º 58
0
    def setUp(self):
        super(TestsNeedingReweave, self).setUp()

        t = self.get_transport()
        # an empty inventory with no revision for testing with.
        repo = self.make_repository('inventory_without_revision')
        repo.lock_write()
        repo.start_write_group()
        inv = Inventory(revision_id='missing')
        inv.root.revision = 'missing'
        repo.add_inventory('missing', inv, [])
        repo.commit_write_group()
        repo.unlock()

        def add_commit(repo, revision_id, parent_ids):
            repo.lock_write()
            repo.start_write_group()
            inv = Inventory(revision_id=revision_id)
            inv.root.revision = revision_id
            root_id = inv.root.file_id
            sha1 = repo.add_inventory(revision_id, inv, parent_ids)
            repo.texts.add_lines((root_id, revision_id), [], [])
            rev = bzrlib.revision.Revision(timestamp=0,
                                           timezone=None,
                                           committer="Foo Bar <*****@*****.**>",
                                           message="Message",
                                           inventory_sha1=sha1,
                                           revision_id=revision_id)
            rev.parent_ids = parent_ids
            repo.add_revision(revision_id, rev)
            repo.commit_write_group()
            repo.unlock()
        # an empty inventory with no revision for testing with.
        # this is referenced by 'references_missing' to let us test
        # that all the cached data is correctly converted into ghost links
        # and the referenced inventory still cleaned.
        repo = self.make_repository('inventory_without_revision_and_ghost')
        repo.lock_write()
        repo.start_write_group()
        repo.add_inventory('missing', inv, [])
        repo.commit_write_group()
        repo.unlock()
        add_commit(repo, 'references_missing', ['missing'])

        # a inventory with no parents and the revision has parents..
        # i.e. a ghost.
        repo = self.make_repository('inventory_one_ghost')
        add_commit(repo, 'ghost', ['the_ghost'])

        # a inventory with a ghost that can be corrected now.
        t.copy_tree('inventory_one_ghost', 'inventory_ghost_present')
        bzrdir_url = self.get_url('inventory_ghost_present')
        bzrdir = BzrDir.open(bzrdir_url)
        repo = bzrdir.open_repository()
        add_commit(repo, 'the_ghost', [])