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)
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))
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))
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")
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")
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)
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()
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())
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)
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
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)
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
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()
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
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
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
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()
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())
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)
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()
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', [])
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
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). """ # Bazaar import bzrlib from bzrlib.branch import Branch from bzrlib.bzrdir import BzrDir from bzrlib.workingtree import WorkingTree try: BzrDir.open(self.repo_location) except bzrlib.errors.NotBranchError: BzrDir.create_branch_convenience(self.repo_location) c = Branch.open(self.repo_location).get_config_stack() c.set('email', '{}@{}'.format(get_current_user(), socket.getfqdn())) self.tree = WorkingTree.open(self.repo_location) delta = self.tree.changes_from(self.tree.basis_tree(), want_unversioned=True) logger.debug('tree `{}`'.format(self.tree)) logger.debug('delta `{}`'.format(delta)) for file_info in delta.unversioned: logger.debug('unversioned [{}]'.format(file_info)) file_name = file_info[0] self.tree.add(file_name) if delta.unversioned: self.tree.commit('Added new unversioned files') else: logger.debug('No unversioned files found') if delta.modified: self.tree.commit('Committed modified files') else: logger.debug('No modified files found')
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', [])
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())
def test_convenience_reconcile_inventory_without_revision_reconcile(self): # smoke test for the all in one ui tool bzrdir_url = self.get_url('inventory_without_revision') bzrdir = BzrDir.open(bzrdir_url) repo = bzrdir.open_repository() if not repo._reconcile_does_inventory_gc: raise TestSkipped('Irrelevant test') reconcile(bzrdir) # now the backup should have it but not the current inventory repo = bzrdir.open_repository() self.check_missing_was_removed(repo)
def test_reweave_inventory_without_revision_and_ghost(self): # actual low level test. d_url = self.get_url('inventory_without_revision_and_ghost') d = BzrDir.open(d_url) repo = d.open_repository() if not repo._reconcile_does_inventory_gc: raise TestSkipped('Irrelevant test') # nothing should have been altered yet : inventories without # revisions are not data loss incurring for current format self.check_thorough_reweave_missing_revision(d, repo.reconcile, thorough=True)
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
def _getUpstreamChangesets(self, sincerev): """ See what other revisions exist upstream and return them """ parent_branch = BzrDir.open(self.repository.repository).open_branch() branch = self._working_tree.branch revisions = branch.missing_revisions(parent_branch) branch.fetch(parent_branch) for revision_id in revisions: yield self._changesetFromRevision(parent_branch, revision_id)
def test_reweave_inventory_preserves_a_revision_with_ghosts(self): d = BzrDir.open(self.get_url('inventory_one_ghost')) reconciler = d.open_repository().reconcile(thorough=True) # no inconsistent parents should have been found: # the lack of a parent for ghost is normal self.assertEqual(0, reconciler.inconsistent_parents) # and one garbage inventories self.assertEqual(0, reconciler.garbage_inventories) # now the current inventory should still have 'ghost' repo = d.open_repository() repo.get_inventory('ghost') self.assertThat(['ghost', 'the_ghost'], MatchesAncestry(repo, 'ghost'))
def test_reweave_inventory_without_revision_reconciler(self): # smoke test for the all in one Reconciler class, # other tests use the lower level repo.reconcile() d_url = self.get_url('inventory_without_revision_and_ghost') d = BzrDir.open(d_url) if not d.open_repository()._reconcile_does_inventory_gc: raise TestSkipped('Irrelevant test') def reconcile(): reconciler = Reconciler(d) reconciler.reconcile() return reconciler self.check_thorough_reweave_missing_revision(d, reconcile)
def checkEmptyReconcile(self, **kwargs): """Check a reconcile on an empty repository.""" self.make_repository('empty') d = BzrDir.open(self.get_url('empty')) # calling on a empty repository should do nothing reconciler = d.find_repository().reconcile(**kwargs) # no inconsistent parents should have been found self.assertEqual(0, reconciler.inconsistent_parents) # and no garbage inventories self.assertEqual(0, reconciler.garbage_inventories) # and no backup weave should have been needed/made. self.checkNoBackupInventory(d)
def do_push(br_from, location, overwrite): """ Update a mirror of a branch. :param br_from: the source branch :param location: the location of the branch that you'd like to update :param overwrite: overwrite target location if it diverged :return: number of revisions pushed """ from bzrlib.bzrdir import BzrDir from bzrlib.transport import get_transport transport = get_transport(location) location_url = transport.base old_rh = [] try: dir_to = BzrDir.open(location_url) br_to = dir_to.open_branch() except errors.NotBranchError: # create a branch. transport = transport.clone('..') try: relurl = transport.relpath(location_url) transport.mkdir(relurl) except errors.NoSuchFile: response = question_dialog(_i18n('Non existing parent directory'), _i18n("The parent directory (%s)\ndoesn't exist. Create?") % location) if response == gtk.RESPONSE_OK: transport.create_prefix() else: return dir_to = br_from.bzrdir.clone(location_url, revision_id=br_from.last_revision()) br_to = dir_to.open_branch() count = len(br_to.revision_history()) else: old_rh = br_to.revision_history() try: tree_to = dir_to.open_workingtree() except errors.NotLocalUrl: # FIXME - what to do here? how should we warn the user? count = br_to.pull(br_from, overwrite) except errors.NoWorkingTree: count = br_to.pull(br_from, overwrite) else: count = tree_to.pull(br_from, overwrite) return count
def test_branch_tree(self): self.run_bzr("init-repo --trees a") self.run_bzr("init --format=default b") file('b/hello', 'wt').write('bar') self.run_bzr("add b/hello") self.run_bzr("commit -m bar b/hello") self.run_bzr('branch b a/c') cdir = BzrDir.open('a/c') cdir.open_branch() self.assertRaises(errors.NoRepositoryPresent, cdir.open_repository) self.failUnlessExists('a/c/hello') cdir.open_workingtree()
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: logger.info('Location [{}] is not a Bazaar branch. Will turn it into one.'.format(self.repo_location)) BzrDir.create_branch_convenience(self.repo_location) c = Branch.open(self.repo_location).get_config_stack() c.set('email', '{}@{}'.format(get_current_user(), socket.getfqdn())) self.tree = WorkingTree.open(self.repo_location) delta = self.tree.changes_from(self.tree.basis_tree(), want_unversioned=True) logger.debug('tree [{}]'.format(self.tree)) logger.debug('delta [{}]'.format(delta)) for file_info in delta.unversioned: logger.debug('unversioned [{}]'.format(file_info)) file_name = file_info[0] self.tree.add(file_name) if delta.unversioned: self.tree.commit('Added new unversioned files') else: logger.debug('No unversioned files found') if delta.modified: self.tree.commit('Committed modified files') else: logger.debug('No modified files found')
def test_reweave_inventory_without_revision(self): # an excess inventory on its own is only reconciled by using thorough d_url = self.get_url('inventory_without_revision') d = BzrDir.open(d_url) repo = d.open_repository() if not repo._reconcile_does_inventory_gc: raise TestSkipped('Irrelevant test') self.checkUnreconciled(d, repo.reconcile()) reconciler = repo.reconcile(thorough=True) # no bad parents self.assertEqual(0, reconciler.inconsistent_parents) # and one garbage inventory self.assertEqual(1, reconciler.garbage_inventories) self.check_missing_was_removed(repo)
def switch_branches(prefix, scheme, old_db_branch, new_db_branch): """Move bzr data from an old to a new branch, leaving old stacked on new. This function is intended to be used just after Ubuntu is released to create (at the bzr level) a new trunk branch for a source package for the next release of the distribution. We move the bzr data to the location for the new branch and replace the trunk branch for the just released version with a stacked branch pointing at the new branch. The procedure is to complicated to be carried out atomically, so if this function is interrupted things may be a little inconsistent (e.g. there might be a branch in the old location, but not stacked on the new location yet). There should be no data loss though. :param prefix: The non-branch id dependent part of the physical path to the branches on disk. :param scheme: The branches should be open-able at a URL of the form ``scheme + :/// + unique_name``. :param old_db_branch: The branch that currently has the trunk bzr data. :param old_db_branch: The new trunk branch. This should not have any presence on disk yet. """ # Move .bzr directory from old to new location, crashing through the # abstraction we usually hide our branch locations behind. old_underlying_path = os.path.join( prefix, branch_id_to_path(old_db_branch.id)) new_underlying_path = os.path.join( prefix, branch_id_to_path(new_db_branch.id)) os.makedirs(new_underlying_path) os.rename( os.path.join(old_underlying_path, '.bzr'), os.path.join(new_underlying_path, '.bzr')) # Create branch at old location -- we use the "clone('null:')" trick to # preserve the format. We have to open at the logical, unique_name-based, # location so that it works to set the stacked on url to '/' + a # unique_name. new_location_bzrdir = BzrDir.open( scheme + ':///' + new_db_branch.unique_name) old_location_bzrdir = new_location_bzrdir.clone( scheme + ':///' + old_db_branch.unique_name, revision_id='null:') # Set the stacked on url for old location. old_location_branch = old_location_bzrdir.open_branch() old_location_branch.set_stacked_on_url('/' + new_db_branch.unique_name) # Pull from new location to old -- this won't actually transfer any # revisions, just update the last revision pointer. old_location_branch.pull(new_location_bzrdir.open_branch())
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)
def detect_bzr_revision(): if __has_bzrlib: b = BzrDir.open(base_path).open_branch() revno, nick = b.revno(), b.nick else: # Windows stand alone installer do not come with bzrlib. We try to # parse the output of bzr then directly try: run_bzr = lambda subcmd: subprocess.Popen( ["bzr",subcmd], stdout=subprocess.PIPE, cwd=base_path ).stdout.read().strip().decode("utf-8") revno = run_bzr("revno") nick = run_bzr("nick") except OSError: return None return "bzr%s[%s] " % (revno, nick)
def detect_bzr_revision(): if __has_bzrlib: b = BzrDir.open(base_path).open_branch() revno, nick = b.revno(), b.nick else: # Windows stand alone installer do not come with bzrlib. We try to # parse the output of bzr then directly try: run_bzr = lambda subcmd: subprocess.Popen( ['bzr', subcmd], stdout=subprocess.PIPE, cwd=base_path ).stdout.read().strip().decode('utf-8') revno = run_bzr('revno') nick = run_bzr('nick') except OSError: return None return 'bzr%s[%s] ' % (revno, nick)
def detect_bzr_revision(): def extract_git_hash(commit_message): # Get the last string in the commit message git_hash = commit_message.split()[-1] # Does it look like a git hash? if re.search(r'^[0-9A-Fa-f]{40}$', git_hash) is not None: # It does; shorten it return git_hash[:7] else: return 'NO_HASH' if __has_bzrlib: try: b = BzrDir.open(base_path).open_branch() revno, nick = b.revno(), b.nick commit_message = b.repository.get_revision( b.last_revision()).message git_hash = extract_git_hash(commit_message) # 1.0~bzr9876[abc0123@trunk] return '{nsv}~bzr{revno}[{git_hash}@{nick}]'.format( nsv=next_stable_version, revno=revno, git_hash=git_hash, nick=nick) except: return None else: # Windows stand alone installer do not come with bzrlib. We try to # parse the output of bzr then directly try: def run_bzr(args): return _communicate_utf8(['bzr'] + args, cwd=base_path).strip() revno = run_bzr(['revno']) nick = run_bzr(['nick']) commit_message = run_bzr(['log', '--limit=1', '--short']) git_hash = extract_git_hash(commit_message) # 1.0~bzr9876[abc0123@trunk] return '{nsv}~bzr{revno}[{git_hash}@{nick}]'.format( nsv=next_stable_version, revno=revno, git_hash=git_hash, nick=nick) except (OSError, subprocess.CalledProcessError, IndexError): return None return None
def create_branches(self): self.build_tree(['base/', 'base/a', 'base/b']) branch = self.init_meta_branch('base') base_tree = branch.bzrdir.open_workingtree() base_tree.lock_write() base_tree.add(['a', 'b']) base_tree.commit('init') base_tree.unlock() child_tree = branch.create_checkout('child') self.check_revno(1, 'child') d = BzrDir.open('child') self.assertNotEqual(None, d.open_branch().get_master_branch()) return base_tree, child_tree
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)
def create(self): """ Create a branch with a working tree at the base directory. If the base directory is inside a Bazaar style "shared repository", it will use that to create a branch and working tree (make sure it allows working trees). """ self.log.info('Initializing new repository in %r...', self.basedir) try: bzrdir = BzrDir.open(self.basedir) except errors.NotBranchError: # really a NotBzrDir error... branch = BzrDir.create_branch_convenience(self.basedir, force_new_tree=True) wtree = branch.bzrdir.open_workingtree() else: bzrdir.create_branch() wtree = bzrdir.create_workingtree() return wtree
def detect_bzr_revision(): if __has_bzrlib: try: b = BzrDir.open(base_path).open_branch() revno, nick = b.revno(), b.nick return 'bzr%s[%s]' % (revno, nick) except: return None else: # Windows stand alone installer do not come with bzrlib. We try to # parse the output of bzr then directly try: def run_bzr(subcmd): return subprocess.Popen( ['bzr', subcmd], stdout=subprocess.PIPE, cwd=base_path ).stdout.read().strip().decode('utf-8') revno = run_bzr('revno') nick = run_bzr('nick') return 'bzr%s[%s]' % (revno, nick) except OSError: return None return None
def _checkoutUpstreamRevision(self, revision): """ Initial checkout of upstream branch, equivalent of 'bzr branch -r', and return the last changeset. """ parent_bzrdir = BzrDir.open(self.repository.repository) parent_branch = parent_bzrdir.open_branch() if revision == "INITIAL": revid = parent_branch.get_rev_id(1) 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)
def pull(self, db_branch_id, target_path, required_format, needs_tree=False, stacked_on_url=None): """Pull down the Bazaar branch of an import to `target_path`. :return: A Bazaar branch for the code import corresponding to the database branch with id `db_branch_id`. """ remote_url = self._getMirrorURL(db_branch_id) try: remote_bzr_dir = BzrDir.open(remote_url) except NotBranchError: local_branch = BzrDir.create_branch_and_repo( target_path, format=required_format) if needs_tree: local_branch.bzrdir.create_workingtree() if stacked_on_url: local_branch.set_stacked_on_url(stacked_on_url) return local_branch # The proper thing to do here would be to call # "remote_bzr_dir.sprout()". But 2a fetch slowly checks which # revisions are in the ancestry of the tip of the remote branch, which # we strictly don't care about, so we just copy the whole thing down # at the vfs level. control_dir = remote_bzr_dir.root_transport.relpath( remote_bzr_dir.transport.abspath('.')) target = get_transport_from_path(target_path) target_control = target.clone(control_dir) target_control.create_prefix() remote_bzr_dir.transport.copy_tree_to_transport(target_control) local_bzr_dir = BzrDir.open_from_transport(target) if local_bzr_dir.needs_format_conversion(format=required_format): try: local_bzr_dir.root_transport.delete_tree('backup.bzr') except NoSuchFile: pass upgrade(target_path, required_format, clean_up=True) if needs_tree: local_bzr_dir.create_workingtree() return local_bzr_dir.open_branch()
def _applyChangeset(self, changeset): """ Apply the given changeset to the working tree """ parent_branch = BzrDir.open(self.repository.repository).open_branch() self._working_tree.lock_write() try: count = self._working_tree.pull(parent_branch, stop_revision=changeset.revision) # XXX: this does not seem to return a true value on conflicts! conflicts = self._working_tree.update() finally: self._working_tree.unlock() try: pulled_revnos = count.new_revno - count.old_revno except AttributeError: # Prior to 0.15 pull returned a simple integer instead of a result object pulled_revnos = count self.log.info('Updated to %r, applied %d changesets', changeset.revision, count) if conflicts: # No conflict handling yet raise ChangesetApplicationFailure('Unsupported: conflicts') return []