def test_file_moves(self): """Test moves""" builder = MergeBuilder(getcwd()) builder.add_dir("1", builder.tree_root, "dir1") builder.add_dir("2", builder.tree_root, "dir2") builder.add_file("3", "1", "file1", "hello1", True) builder.add_file("4", "1", "file2", "hello2", True) builder.add_file("5", "1", "file3", "hello3", True) builder.change_parent("3", other="2") builder.change_parent("4", this="2") builder.change_parent("5", base="2") builder.merge() builder.cleanup() builder = MergeBuilder(getcwd()) builder.add_dir("1", builder.tree_root, "dir1") builder.add_dir("2", builder.tree_root, "dir2") builder.add_dir("3", builder.tree_root, "dir3") builder.add_file("4", "1", "file1", "hello1", False) builder.change_parent("4", other="2", this="3") conflicts = builder.merge() path2 = pathjoin("dir2", "file1") path3 = pathjoin("dir3", "file1") self.assertEqual(conflicts, [PathConflict(path3, path2, "4")]) builder.cleanup()
def _find_plugin_module(dir, name): """Check if there is a valid python module that can be loaded as a plugin. :param dir: The directory where the search is performed. :param path: An existing file path, either a python file or a package directory. :return: (name, path, description) name is the module name, path is the file to load and description is the tuple returned by imp.get_suffixes(). """ path = osutils.pathjoin(dir, name) if os.path.isdir(path): # Check for a valid __init__.py file, valid suffixes depends on -O and # can be .py, .pyc and .pyo for suffix, mode, kind in imp.get_suffixes(): if kind not in (imp.PY_SOURCE, imp.PY_COMPILED): # We don't recognize compiled modules (.so, .dll, etc) continue init_path = osutils.pathjoin(path, '__init__' + suffix) if os.path.isfile(init_path): return name, init_path, (suffix, mode, kind) else: for suffix, mode, kind in imp.get_suffixes(): if name.endswith(suffix): # Clean up the module name name = name[:-len(suffix)] if kind == imp.C_EXTENSION and name.endswith('module'): name = name[:-len('module')] return name, path, (suffix, mode, kind) # There is no python module here return None, None, (None, None, None)
def test_pull_show_base(self): """bzr pull supports --show-base see https://bugs.launchpad.net/bzr/+bug/202374""" # create two trees with conflicts, setup conflict, check that # conflicted file looks correct a_tree = self.example_branch('a') b_tree = a_tree.bzrdir.sprout('b').open_workingtree() with open(osutils.pathjoin('a', 'hello'), 'wt') as f: f.write('fee') a_tree.commit('fee') with open(osutils.pathjoin('b', 'hello'), 'wt') as f: f.write('fie') out, err = self.run_bzr(['pull', '-d', 'b', 'a', '--show-base']) # check for message here self.assertEqual( err, ' M hello\nText conflict in hello\n1 conflicts encountered.\n') self.assertEqualDiff( '<<<<<<< TREE\n' 'fie||||||| BASE-REVISION\n' 'foo=======\n' 'fee>>>>>>> MERGE-SOURCE\n', open(osutils.pathjoin('b', 'hello')).read())
def branch_iterator(self, target_root=None): if len(self.config) == 0: # branch not have externals configuration return self.bound = True if not target_root: target_root = self.branch.get_bound_location() if not target_root: self.bound = False target_root = self.branch.get_parent() if not target_root: # support new braches with no parent yet target_root = self.branch.base for arg in self.config: # url directory [revisionspec] location = self._relurljoin(target_root, arg[0]) if target_root.startswith('file:///'): # try to pull externals from the parent for the feature branch path = pathjoin(local_path_from_url(target_root), arg[1]) if isdir(path): location = self._relpath(path) else: # parent is local master branch if location.startswith('file:///'): location = self._relpath(local_path_from_url(location)) check_legal_path(arg[1]) rel_path = self._relpath(pathjoin(self.root, arg[1])) revision = None if len(arg) > 2: revision = arg[2] yield location, rel_path, revision
def test_pull_show_base(self): """bzr pull supports --show-base see https://bugs.launchpad.net/bzr/+bug/202374""" # create two trees with conflicts, setup conflict, check that # conflicted file looks correct a_tree = self.example_branch('a') b_tree = a_tree.bzrdir.sprout('b').open_workingtree() with open(osutils.pathjoin('a', 'hello'),'wt') as f: f.write('fee') a_tree.commit('fee') with open(osutils.pathjoin('b', 'hello'),'wt') as f: f.write('fie') out,err=self.run_bzr(['pull','-d','b','a','--show-base']) # check for message here self.assertEqual( err, ' M hello\nText conflict in hello\n1 conflicts encountered.\n') self.assertEqualDiff('<<<<<<< TREE\n' 'fie||||||| BASE-REVISION\n' 'foo=======\n' 'fee>>>>>>> MERGE-SOURCE\n', open(osutils.pathjoin('b', 'hello')).read())
def test_pull(self): # Make sure we can pull from paths that can't be encoded dirname1 = self.info['directory'] dirname2 = self.info['directory'] + '2' url1 = urlutils.local_path_to_url(dirname1) url2 = urlutils.local_path_to_url(dirname2) out_bzrdir = self.wt.bzrdir.sprout(url1) out_bzrdir.sprout(url2) self.build_tree_contents( [(osutils.pathjoin(dirname1, "a"), 'different text\n')]) self.wt.commit('mod a') txt = self.run_bzr_decode('pull', working_dir=dirname2) expected = osutils.pathjoin(osutils.getcwd(), dirname1) self.assertEqual(u'Using saved parent location: %s/\n' 'No revisions or tags to pull.\n' % (expected,), txt) self.build_tree_contents( [(osutils.pathjoin(dirname1, 'a'), 'and yet more\n')]) self.wt.commit(u'modifying a by ' + self.info['committer']) # We should be able to pull, even if our encoding is bad self.run_bzr_decode('pull --verbose', encoding='ascii', working_dir=dirname2)
def test_file_moves(self): """Test moves""" builder = MergeBuilder(getcwd()) builder.add_dir("1", builder.tree_root, "dir1") builder.add_dir("2", builder.tree_root, "dir2") builder.add_file("3", "1", "file1", "hello1", True) builder.add_file("4", "1", "file2", "hello2", True) builder.add_file("5", "1", "file3", "hello3", True) builder.change_parent("3", other="2") builder.change_parent("4", this="2") builder.change_parent("5", base="2") builder.merge() builder.cleanup() builder = MergeBuilder(getcwd()) builder.add_dir("1", builder.tree_root, "dir1") builder.add_dir("2", builder.tree_root, "dir2") builder.add_dir("3", builder.tree_root, "dir3") builder.add_file("4", "1", "file1", "hello1", False) builder.change_parent("4", other="2", this="3") conflicts = builder.merge() path2 = pathjoin('dir2', 'file1') path3 = pathjoin('dir3', 'file1') self.assertEqual(conflicts, [PathConflict(path3, path2, '4')]) builder.cleanup()
def test_pull(self): # Make sure we can pull from paths that can't be encoded dirname1 = self.info['directory'] dirname2 = self.info['directory'] + '2' url1 = urlutils.local_path_to_url(dirname1) url2 = urlutils.local_path_to_url(dirname2) out_bzrdir = self.wt.bzrdir.sprout(url1) out_bzrdir.sprout(url2) self.build_tree_contents( [(osutils.pathjoin(dirname1, "a"), 'different text\n')]) self.wt.commit('mod a') txt = self.run_bzr_decode('pull', working_dir=dirname2) expected = osutils.pathjoin(osutils.getcwd(), dirname1) self.assertEqual(u'Using saved location: %s/\n' 'No revisions to pull.\n' % (expected,), txt) self.build_tree_contents( [(osutils.pathjoin(dirname1, 'a'), 'and yet more\n')]) self.wt.commit(u'modifying a by ' + self.info['committer']) # We should be able to pull, even if our encoding is bad self.run_bzr_decode('pull --verbose', encoding='ascii', working_dir=dirname2)
def commit(self, mutable_tree): # BUG: not run recursively if in above branch not have changes if disable_hooks or not self.read_config(): return from bzrlib.workingtree import WorkingTree snapshot = [] for arg in self.config: # url directory [revisionspec] wt = WorkingTree.open(pathjoin(self.root, arg[1])) if wt.has_changes(wt.basis_tree()): cmd = ['ci'] os.chdir(wt.basedir) try: run_bzr_catch_user_errors(cmd) finally: os.chdir(self.cwd) if len(arg) < 3: arg.append('') arg[2] = 'revid:' + wt.last_revision() arg[1] = self._quoted_if_need(arg[1]) snapshot.append(' '.join(arg).encode('utf-8')) path = pathjoin(self.root, SNAPSHOT_PATH) f = open(path, 'w') try: f.write('\n'.join(snapshot)) finally: f.close()
def example_branch(self, path='.'): tree = self.make_branch_and_tree(path) self.build_tree_contents([(pathjoin(path, 'hello'), 'foo'), (pathjoin(path, 'goodbye'), 'baz')]) tree.add('hello') tree.commit(message='setup') tree.add('goodbye') tree.commit(message='setup') return tree
def example_branch(self, path='.'): tree = self.make_branch_and_tree(path) self.build_tree_contents([ (osutils.pathjoin(path, 'hello'), 'foo'), (osutils.pathjoin(path, 'goodbye'), 'baz')]) tree.add('hello') tree.commit(message='setup') tree.add('goodbye') tree.commit(message='setup') return tree
def test_canonicalize_path(self): """Canonicalizing paths should be fast.""" wt = self.make_kernel_like_tree(link_working=True) paths = [] for dirpath, dirnames, filenames in os.walk('.'): paths.extend(pathjoin(dirpath, d) for d in dirnames) paths.extend(pathjoin(dirpath, f) for f in filenames) tt = TreeTransform(wt) self.time(self.canonicalize_paths, tt, paths) tt.finalize()
def test_layered_rename(self): """Rename both child and parent at same time""" tree =self.make_branch_and_tree('.') os.mkdir('dirname1') tree.add('dirname1') filename = pathjoin('dirname1', 'name1') file(filename, 'wb').write('Hello') tree.add(filename) tree.commit(message="hello") filename2 = pathjoin('dirname1', 'name2') tree.rename_one(filename, filename2) tree.rename_one('dirname1', 'dirname2') transform_tree(tree, tree.branch.basis_tree())
def run(self, from_location, to_location, revision=None): branch = Branch.open_containing('.')[0] root = local_path_from_url(branch.base) # select what do it if isdir(pathjoin(root, to_location, '.bzr')) or isdir(pathjoin(root, to_location, '.svn')): if branch.get_bound_location(): cmd = ['update', to_location] else: cmd = ['pull', from_location, '--directory', to_location] else: if branch.get_bound_location(): cmd = ['checkout', from_location, to_location] else: cmd = ['branch', from_location, to_location] # command branch don't create recursive directory dirs = to_location.rpartition('/') if dirs[0] != '' and not isdir(dirs[0]): os.makedirs(dirs[0].encode(get_user_encoding())) # if use revision options but not for 'update' if revision is not None:# and cmd[0] != 'update': cmd += ['--revision', revision[0].user_spec] note('Add external ' + ' '.join(cmd)) run_bzr_catch_user_errors(cmd) bzrmeta = pathjoin(root, '.bzrmeta') if not isdir(bzrmeta): os.mkdir(bzrmeta) # add new branch to config and snapshot files line = from_location + ' ' + self._quoted_if_need(to_location) if revision: line += ' ' + revision[0].user_spec self._add_to_file(root, externals.CONFIG_PATH, line) self._add_to_file(root, externals.SNAPSHOT_PATH, line) # add ignore mask from bzrlib import IGNORE_FILENAME self._add_to_file(root, IGNORE_FILENAME, './' + to_location) # add config files to repository cmd = ['add', '.bzrignore', '.bzrmeta/externals', '.bzrmeta/externals-snapshot'] run_bzr_catch_user_errors(cmd)
def _load_from_file(topic_name): """Load help from a file. Topics are expected to be txt files in bzrlib.help_topics. """ resource_name = osutils.pathjoin("en", "%s.txt" % (topic_name,)) return osutils.resource_string('bzrlib.help_topics', resource_name)
def new_path(self, old_path): """Get the new_path (path in the target_tree) for the file at old_path in the base tree. """ if old_path[:1] in ('\\', '/'): raise ValueError(old_path) new_path = self._renamed_r.get(old_path) if new_path is not None: return new_path if new_path in self._renamed: return None dirname, basename = os.path.split(old_path) if dirname != '': new_dir = self.new_path(dirname) if new_dir is None: new_path = None else: new_path = pathjoin(new_dir, basename) else: new_path = old_path #If the old path wasn't in renamed, the new one shouldn't be in #renamed_r if new_path in self._renamed: return None return new_path
def test_update_conflicts_returns_2(self): self.make_branch_and_tree('branch') # make two checkouts self.run_bzr('checkout --lightweight branch checkout') self.build_tree(['checkout/file']) self.run_bzr('add checkout/file') self.run_bzr('commit -m add-file checkout') self.run_bzr('checkout --lightweight branch checkout2') # now alter file in checkout a_file = file('checkout/file', 'wt') a_file.write('Foo') a_file.close() self.run_bzr('commit -m checnge-file checkout') # now checkout2 should be out of date # make a local change to file a_file = file('checkout2/file', 'wt') a_file.write('Bar') a_file.close() out,err = self.run_bzr('update checkout2', retcode=1) self.assertEqualDiff(''' M file Text conflict in file 1 conflicts encountered. Updated to revision 2 of branch %s ''' % osutils.pathjoin(self.test_dir, 'branch',), err) self.assertEqual('', out)
def new_path(self, old_path): """Get the new_path (path in the target_tree) for the file at old_path in the base tree. """ if old_path[:1] in ('\\', '/'): raise ValueError(old_path) new_path = self._renamed_r.get(old_path) if new_path is not None: return new_path if new_path in self._renamed: return None dirname,basename = os.path.split(old_path) if dirname != '': new_dir = self.new_path(dirname) if new_dir is None: new_path = None else: new_path = pathjoin(new_dir, basename) else: new_path = old_path #If the old path wasn't in renamed, the new one shouldn't be in #renamed_r if new_path in self._renamed: return None return new_path
def test_plugin_help_shows_plugin(self): # Create a test plugin os.mkdir('plugin_test') f = open(osutils.pathjoin('plugin_test', 'myplug.py'), 'w') f.write("""\ from bzrlib import commands class cmd_myplug(commands.Command): __doc__ = '''Just a simple test plugin.''' aliases = ['mplg'] def run(self): print 'Hello from my plugin' """) f.close() try: # Check its help bzrlib.plugin.load_from_path(['plugin_test']) bzrlib.commands.register_command(bzrlib.plugins.myplug.cmd_myplug) help = self.run_bzr('help myplug')[0] self.assertContainsRe(help, 'plugin "myplug"') help = self.split_help_commands()['myplug'] self.assertContainsRe(help, '\[myplug\]') finally: # unregister command if 'myplug' in bzrlib.commands.plugin_cmds: bzrlib.commands.plugin_cmds.remove('myplug') # remove the plugin 'myplug' if getattr(bzrlib.plugins, 'myplug', None): delattr(bzrlib.plugins, 'myplug')
def test_plugin_help_shows_plugin(self): # Create a test plugin os.mkdir('plugin_test') f = open(osutils.pathjoin('plugin_test', 'myplug.py'), 'w') f.write("""\ from bzrlib import commands class cmd_myplug(commands.Command): __doc__ = '''Just a simple test plugin.''' aliases = ['mplg'] def run(self): print 'Hello from my plugin' """ ) f.close() try: # Check its help bzrlib.plugin.load_from_path(['plugin_test']) bzrlib.commands.register_command( bzrlib.plugins.myplug.cmd_myplug) help = self.run_bzr('help myplug')[0] self.assertContainsRe(help, 'plugin "myplug"') help = self.split_help_commands()['myplug'] self.assertContainsRe(help, '\[myplug\]') finally: # unregister command if 'myplug' in bzrlib.commands.plugin_cmds: bzrlib.commands.plugin_cmds.remove('myplug') # remove the plugin 'myplug' if getattr(bzrlib.plugins, 'myplug', None): delattr(bzrlib.plugins, 'myplug')
def _load_from_file(topic_name): """Load help from a file. Topics are expected to be txt files in bzrlib.help_topics. """ resource_name = osutils.pathjoin("en", "%s.txt" % (topic_name, )) return osutils.resource_string('bzrlib.help_topics', resource_name)
def get_source_files(self, extensions=None): """Yield all source files for bzr and bzrlib :param our_files_only: If true, exclude files from included libraries or plugins. """ bzrlib_dir = self.get_bzrlib_dir() if extensions is None: extensions = ('.py', ) # This is the front-end 'bzr' script bzr_path = self.get_bzr_path() yield bzr_path for root, dirs, files in os.walk(bzrlib_dir): for d in dirs: if d.endswith('.tmp'): dirs.remove(d) for f in files: for extension in extensions: if f.endswith(extension): break else: # Did not match the accepted extensions continue yield osutils.pathjoin(root, f)
def _open_crash_file(): crash_dir = config.crash_dir() if not osutils.isdir(crash_dir): # on unix this should be /var/crash and should already exist; on # Windows or if it's manually configured it might need to be created, # and then it should be private os.makedirs(crash_dir, mode=0600) date_string = time.strftime('%Y-%m-%dT%H:%M', time.gmtime()) # XXX: getuid doesn't work on win32, but the crash directory is per-user if sys.platform == 'win32': user_part = '' else: user_part = '.%d' % os.getuid() filename = osutils.pathjoin( crash_dir, 'bzr%s.%s.crash' % ( user_part, date_string)) # be careful here that people can't play tmp-type symlink mischief in the # world-writable directory return filename, os.fdopen( os.open(filename, os.O_WRONLY|os.O_CREAT|os.O_EXCL, 0600), 'wb')
def _default_to_location(self, from_location): """Work out a good To location give a From location. :return: the To location or None if unsure """ # We want to avoid opening the from location here so # we 'guess' the basename using some simple heuristics from_location = from_location.replace('\\', '/').rstrip('/') if from_location.find('/') >= 0: basename = osutils.basename(from_location) else: # Handle 'directory services' like lp: ds_sep = from_location.find(':') if ds_sep >= 0: basename = from_location[ds_sep + 1:] else: return None # Calculate the To location and check it's not the same as the # From location. to_location = osutils.pathjoin(self.parent_dir, basename) if to_location == from_location: return None else: return to_location
def from_args(klass, diff_writer, revision=None, all=False, file_list=None, message=None, directory=None, destroy=False): """Create a shelver from commandline arguments. The returned shelver wil have a work_tree that is locked and should be unlocked. :param revision: RevisionSpec of the revision to compare to. :param all: If True, shelve all changes without prompting. :param file_list: If supplied, only files in this list may be shelved. :param message: The message to associate with the shelved changes. :param directory: The directory containing the working tree. :param destroy: Change the working tree without storing the shelved changes. """ if directory is None: directory = u'.' elif file_list: file_list = [osutils.pathjoin(directory, f) for f in file_list] tree, path = workingtree.WorkingTree.open_containing(directory) # Ensure that tree is locked for the lifetime of target_tree, as # target tree may be reading from the same dirstate. tree.lock_tree_write() try: target_tree = builtins._get_one_revision_tree('shelf2', revision, tree.branch, tree) files = tree.safe_relpath_files(file_list) return klass(tree, target_tree, diff_writer, all, all, files, message, destroy) finally: tree.unlock()
def test_update_conflicts_returns_2(self): self.make_branch_and_tree('branch') # make two checkouts self.run_bzr('checkout --lightweight branch checkout') self.build_tree(['checkout/file']) self.run_bzr('add checkout/file') self.run_bzr('commit -m add-file checkout') self.run_bzr('checkout --lightweight branch checkout2') # now alter file in checkout a_file = file('checkout/file', 'wt') a_file.write('Foo') a_file.close() self.run_bzr('commit -m checnge-file checkout') # now checkout2 should be out of date # make a local change to file a_file = file('checkout2/file', 'wt') a_file.write('Bar') a_file.close() out, err = self.run_bzr('update checkout2', retcode=1) self.assertEqualDiff( ''' M file Text conflict in file 1 conflicts encountered. Updated to revision 2 of branch %s ''' % osutils.pathjoin( self.test_dir, 'branch', ), err) self.assertEqual('', out)
def get_source_files(self, extensions=None): """Yield all source files for bzr and bzrlib :param our_files_only: If true, exclude files from included libraries or plugins. """ bzrlib_dir = self.get_bzrlib_dir() if extensions is None: extensions = ('.py',) # This is the front-end 'bzr' script bzr_path = self.get_bzr_path() yield bzr_path for root, dirs, files in os.walk(bzrlib_dir): for d in dirs: if d.endswith('.tmp'): dirs.remove(d) for f in files: for extension in extensions: if f.endswith(extension): break else: # Did not match the accepted extensions continue yield osutils.pathjoin(root, f)
def merge_into_helper(location, subdir, this_location='.'): """Handle the command line functionality, etc.""" import os wt, subdir_relpath = workingtree.WorkingTree.open_containing( osutils.pathjoin(this_location, subdir)) branch_to_merge = branch.Branch.open(location) wt.lock_write() branch_to_merge.lock_read() try: # 'subdir' is given relative to 'this_location', convert it back into a # path relative to wt.basedir. This also normalizes the path, so things # like '.' and '..' are removed. target_tree = branch_to_merge.basis_tree() target_tree.lock_read() try: merger = MergeIntoMerger(this_tree=wt, other_tree=target_tree, other_branch=branch_to_merge, target_subdir=subdir_relpath, ) merger.set_base_revision(revision.NULL_REVISION, branch_to_merge) conflicts = merger.do_merge() merger.set_pending() finally: target_tree.unlock() finally: branch_to_merge.unlock() wt.unlock() return conflicts
def test_update_up_to_date_light_checkout(self): self.make_branch_and_tree('branch') self.run_bzr('checkout --lightweight branch checkout') out, err = self.run_bzr('update checkout') self.assertEqual('Tree is up to date at revision 0 of branch %s\n' % osutils.pathjoin(self.test_dir, 'branch'), err) self.assertEqual('', out)
def test_update_up_to_date_light_checkout(self): self.make_branch_and_tree('branch') self.run_bzr('checkout --lightweight branch checkout') out, err = self.run_bzr('update checkout') self.assertEqual( 'Tree is up to date at revision 0 of branch %s\n' % osutils.pathjoin(self.test_dir, 'branch'), err) self.assertEqual('', out)
def _get_cache_dir(self): """Get the directory to use for caching this tree :return: The path to use for caching. If None, caching is disabled """ if self._cache_root is None: return None return osutils.pathjoin(self._cache_root, self._tree_name)
def _get_base_file_id(self, path, parent_ie): """Look for a file id in the base branch. First, if the base tree has the parent directory, we look for a file with the same name in that directory. Else, we look for an entry in the base tree with the same path. """ if self.base_tree.has_id(parent_ie.file_id): base_path = osutils.pathjoin( self.base_tree.id2path(parent_ie.file_id), osutils.basename(path)) base_id = self.base_tree.path2id(base_path) if base_id is not None: return (base_id, base_path) full_base_path = osutils.pathjoin(self.base_path, path) # This may return None, but it is our last attempt return self.base_tree.path2id(full_base_path), full_base_path
def test_repository_deprecation_warning_suppressed_locations(self): """Old formats give a warning""" self.make_obsolete_repo('foo') conf = config.LocationStack(osutils.pathjoin(self.test_dir, 'foo')) conf.set('suppress_warnings', 'format_deprecation') self.enable_deprecation_warning() out, err = self.run_bzr('status', working_dir='foo') self.check_warning(False)
def zip_exporter(tree, dest, root): """ Export this tree to a new zip file. `dest` will be created holding the contents of this tree; if it already exists, it will be overwritten". """ import time now = time.localtime()[:6] mutter('export version %r', tree) compression = zipfile.ZIP_DEFLATED zipf = zipfile.ZipFile(dest, "w", compression) inv = tree.inventory try: entries = inv.iter_entries() entries.next() # skip root for dp, ie in entries: # The .bzr* namespace is reserved for "magic" files like # .bzrignore and .bzrrules - do not export these if dp.startswith(".bzr"): continue file_id = ie.file_id mutter(" export {%s} kind %s to %s", file_id, ie.kind, dest) # zipfile.ZipFile switches all paths to forward # slashes anyway, so just stick with that. filename = osutils.pathjoin(root, dp).encode('utf8') if ie.kind == "file": zinfo = zipfile.ZipInfo(filename=filename, date_time=now) zinfo.compress_type = compression zinfo.external_attr = _FILE_ATTR zipf.writestr(zinfo, tree.get_file_text(file_id)) elif ie.kind == "directory": # Directories must contain a trailing slash, to indicate # to the zip routine that they are really directories and # not just empty files. zinfo = zipfile.ZipInfo(filename=filename + '/', date_time=now) zinfo.compress_type = compression zinfo.external_attr = _DIR_ATTR zipf.writestr(zinfo, '') elif ie.kind == "symlink": zinfo = zipfile.ZipInfo(filename=(filename + '.lnk'), date_time=now) zinfo.compress_type = compression zinfo.external_attr = _FILE_ATTR zipf.writestr(zinfo, ie.symlink_target) zipf.close() except UnicodeEncodeError: zipf.close() os.remove(dest) from bzrlib.errors import BzrError raise BzrError("Can't export non-ascii filenames to zip")
def new_path(file_id): if fild_id in inventory_change: return inventory_change[file_id] else: parent = parent_id(file_id) if parent is None: return orig_inventory[file_id] dirname = new_path(parent) return pathjoin(dirname, os.path.basename(orig_inventory[file_id]))
def test_relpath(self): """test for branch path lookups bzrlib.osutils._relpath do a simple but subtle job: given a path (either relative to cwd or absolute), work out if it is inside a branch and return the path relative to the base. """ import tempfile savedir = os.getcwdu() dtmp = tempfile.mkdtemp() # On Mac OSX, /tmp actually expands to /private/tmp dtmp = realpath(dtmp) def rp(p): return relpath(dtmp, p) try: # check paths inside dtmp while standing outside it self.assertEqual(rp(pathjoin(dtmp, 'foo')), 'foo') # root = nothing self.assertEqual(rp(dtmp), '') self.assertRaises(PathNotChild, rp, '/etc') # now some near-miss operations -- note that # os.path.commonprefix gets these wrong! self.assertRaises(PathNotChild, rp, dtmp.rstrip('\\/') + '2') self.assertRaises(PathNotChild, rp, dtmp.rstrip('\\/') + '2/foo') # now operations based on relpath of files in current # directory, or nearby os.chdir(dtmp) self.assertEqual(rp('foo/bar/quux'), 'foo/bar/quux') self.assertEqual(rp('foo'), 'foo') self.assertEqual(rp('./foo'), 'foo') self.assertEqual(rp(abspath('foo')), 'foo') self.assertRaises(PathNotChild, rp, '../foo') finally: os.chdir(savedir) osutils.rmtree(dtmp)
def _probe(self): if CaseInsCasePresFilenameFeature.available(): return False from bzrlib import tests if tests.TestCaseWithMemoryTransport.TEST_ROOT is None: root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp') tests.TestCaseWithMemoryTransport.TEST_ROOT = root else: root = tests.TestCaseWithMemoryTransport.TEST_ROOT tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='', dir=root) name_a = osutils.pathjoin(tdir, 'a') name_A = osutils.pathjoin(tdir, 'A') os.mkdir(name_a) result = osutils.isdir(name_A) tests._rmtree_temp_dir(tdir) return result
def get_host_key(self): if self._host_key is None: key_file = osutils.pathjoin(self._homedir, 'test_rsa.key') f = open(key_file, 'w') try: f.write(STUB_SERVER_KEY) finally: f.close() self._host_key = paramiko.RSAKey.from_private_key_file(key_file) return self._host_key
def _make_readonly(self): """ Make the contents of the temporary directory read-only. """ if self.readonly: for (directory, subdirs, files) in os.walk(self.path): for file in files: osutils.make_readonly(osutils.pathjoin(directory, file)) return
def wt(name): path = pathjoin(self.dir, name) os.mkdir(path) wt = controldir.ControlDir.create_standalone_workingtree(path) # the tests perform pulls, so need a branch that is writeable. wt.lock_write() wt.set_root_id(self.tree_root) wt.flush() tt = TreeTransform(wt) return wt, tt
def test_file_path(self): # Create a directory structure fname = self.info['filename'] dirname = self.info['directory'] self.build_tree_contents([('base/', ), (osutils.pathjoin('base', '%s/' % (dirname, )), )]) self.wt.add('base') self.wt.add('base/' + dirname) path = osutils.pathjoin('base', dirname, fname) self.wt.rename_one(fname, path) self.wt.commit('moving things around') txt = self.run_bzr_decode(['file-path', path]) # TODO: jam 20060106 We don't support non-ascii file ids yet, # so there is nothing which would fail in ascii encoding # This *should* be retcode=3 txt = self.run_bzr_decode(['file-path', path], encoding='ascii')
def test_add_in_nonascii_branch(self): """Test adding in a non-ASCII branch.""" br_dir = u"\u1234" try: wt = self.make_branch_and_tree(br_dir) except UnicodeEncodeError: raise TestSkipped("filesystem can't accomodate nonascii names") return with file(pathjoin(br_dir, "a"), "w") as f: f.write("hello") wt.add(["a"], ["a-id"])
def test_file_path(self): # Create a directory structure fname = self.info['filename'] dirname = self.info['directory'] self.build_tree_contents([ ('base/', ), (osutils.pathjoin('base', '%s/' % (dirname,)), )]) self.wt.add('base') self.wt.add('base/'+dirname) path = osutils.pathjoin('base', dirname, fname) self.wt.rename_one(fname, path) self.wt.commit('moving things around') txt = self.run_bzr_decode(['file-path', path]) # TODO: jam 20060106 We don't support non-ascii file ids yet, # so there is nothing which would fail in ascii encoding # This *should* be retcode=3 txt = self.run_bzr_decode(['file-path', path], encoding='ascii')
def test_add_not_found(self): """Test add when the input file doesn't exist.""" wt = self.make_branch_and_tree('.') # create a file on disk with the mixed-case name self.build_tree(['MixedCaseParent/', 'MixedCaseParent/MixedCase']) expected_fname = pathjoin(wt.basedir, "MixedCaseParent", "notfound") run_script(self, """ $ bzr add mixedcaseparent/notfound 2>bzr: ERROR: No such file: %s """ % (repr(expected_fname),))
def test_add_not_found(self): """Test add when the input file doesn't exist.""" wt = self.make_branch_and_tree('.') # create a file on disk with the mixed-case name self.build_tree(['MixedCaseParent/', 'MixedCaseParent/MixedCase']) expected_fname = pathjoin(wt.basedir, "MixedCaseParent", "notfound") run_script( self, """ $ bzr add mixedcaseparent/notfound 2>bzr: ERROR: No such file: %s """ % (repr(expected_fname), ))
def test_cd_dir_and_back_home(self): self.assertEqual(self.test_dir, osutils.getcwd()) self.run_script(""" $ mkdir dir $ cd dir """) self.assertEqual(osutils.pathjoin(self.test_dir, 'dir'), osutils.getcwd()) self.run_script('$ cd') self.assertEqual(self.test_dir, osutils.getcwd())
def test_view_on_update(self): tree_1, tree_2 = self.make_abc_tree_and_clone_with_ab_view() self.run_bzr("bind ../tree_1", working_dir='tree_2') out, err = self.run_bzr('update', working_dir='tree_2') self.assertEqualDiff( """Operating on whole tree but only reporting on 'my' view. M a All changes applied successfully. Updated to revision 2 of branch %s """ % osutils.pathjoin(self.test_dir, 'tree_1'), err) self.assertEqual("", out)
def prepare_tarball_item(tree, root, final_path, tree_path, entry, force_mtime=None): """Prepare a tarball item for exporting :param tree: Tree to export :param final_path: Final path to place item :param tree_path: Path for the entry in the tree :param entry: Entry to export :param force_mtime: Option mtime to force, instead of using tree timestamps. Returns a (tarinfo, fileobj) tuple """ filename = osutils.pathjoin(root, final_path).encode('utf8') item = tarfile.TarInfo(filename) if force_mtime is not None: item.mtime = force_mtime else: item.mtime = tree.get_file_mtime(entry.file_id, tree_path) if entry.kind == "file": item.type = tarfile.REGTYPE if tree.is_executable(entry.file_id, tree_path): item.mode = 0755 else: item.mode = 0644 # This brings the whole file into memory, but that's almost needed for # the tarfile contract, which wants the size of the file up front. We # want to make sure it doesn't change, and we need to read it in one # go for content filtering. content = tree.get_file_text(entry.file_id, tree_path) item.size = len(content) fileobj = StringIO.StringIO(content) elif entry.kind == "directory": item.type = tarfile.DIRTYPE item.name += '/' item.size = 0 item.mode = 0755 fileobj = None elif entry.kind == "symlink": item.type = tarfile.SYMTYPE item.size = 0 item.mode = 0755 item.linkname = tree.get_symlink_target(entry.file_id, tree_path) fileobj = None else: raise errors.BzrError("don't know how to export {%s} of kind %r" % (entry.file_id, entry.kind)) return (item, fileobj)